Skip to content

Commit

Permalink
Adição do endpoint de autenticação
Browse files Browse the repository at this point in the history
  • Loading branch information
MateusCosta committed Sep 3, 2019
1 parent 6f83583 commit 3848266
Show file tree
Hide file tree
Showing 11 changed files with 247 additions and 5 deletions.
41 changes: 41 additions & 0 deletions WebApiAuthenticationJWT/Controllers/AuthenticationController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using WebApiAuthenticationJWT.Models;
using WebApiAuthenticationJWT.Services.Interfaces;

namespace WebApiAuthenticationJWT.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AuthenticationController : Controller
{
private readonly IAuthenticateService _authService;
public AuthenticationController(IAuthenticateService authService)
{
_authService = authService;
}

[AllowAnonymous]
[HttpPost, Route("request")]
public IActionResult RequestToken([FromBody] TokenRequest request)
{

if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}

string token;
if (_authService.IsAuthenticated(request, out token))
{
return Ok(token);
}

return BadRequest("Invalid Request");
}
}
}
28 changes: 28 additions & 0 deletions WebApiAuthenticationJWT/Models/TokenManagement.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApiAuthenticationJWT.Models
{
[JsonObject("tokenManagement")]
public class TokenManagement
{
[JsonProperty("secret")]
public string Secret { get; set; }

[JsonProperty("issuer")]
public string Issuer { get; set; }

[JsonProperty("audience")]
public string Audience { get; set; }

[JsonProperty("accessExpiration")]
public int AccessExpiration { get; set; }

[JsonProperty("refreshExpiration")]
public int RefreshExpiration { get; set; }

}
}
21 changes: 21 additions & 0 deletions WebApiAuthenticationJWT/Models/TokenRequest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace WebApiAuthenticationJWT.Models
{
public class TokenRequest
{
[Required]
[JsonProperty("username")]
public string Username { get; set; }


[Required]
[JsonProperty("password")]
public string Password { get; set; }
}
}
20 changes: 20 additions & 0 deletions WebApiAuthenticationJWT/Models/User.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApiAuthenticationJWT.Models
{
public class User
{
public int Id { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string PasswordHash { get; set; }
public string Role { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApiAuthenticationJWT.Models;

namespace WebApiAuthenticationJWT.Services.Interfaces
{
public interface IAuthenticateService
{
bool IsAuthenticated(TokenRequest request, out string token);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApiAuthenticationJWT.Services.Interfaces
{
public interface IUserManagementService
{
bool IsValidUser(string username, string password);
}
}
51 changes: 51 additions & 0 deletions WebApiAuthenticationJWT/Services/TokenAuthenticationService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using WebApiAuthenticationJWT.Models;
using WebApiAuthenticationJWT.Services.Interfaces;

namespace WebApiAuthenticationJWT.Services
{
public class TokenAuthenticationService: IAuthenticateService
{
private readonly IUserManagementService _userManagementService;
private readonly TokenManagement _tokenManagement;

public TokenAuthenticationService(IUserManagementService service, IOptions<TokenManagement> tokenManagement)
{
_userManagementService = service;
_tokenManagement = tokenManagement.Value;
}

public bool IsAuthenticated(TokenRequest request, out string token)
{

token = string.Empty;
if (!_userManagementService.IsValidUser(request.Username, request.Password)) return false;

var claim = new[]
{
new Claim(ClaimTypes.Name, request.Username)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_tokenManagement.Secret));
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

var jwtToken = new JwtSecurityToken(
_tokenManagement.Issuer,
_tokenManagement.Audience,
claim,
expires: DateTime.Now.AddMinutes(_tokenManagement.AccessExpiration),
signingCredentials: credentials
);
token = new JwtSecurityTokenHandler().WriteToken(jwtToken);
return true;

}
}
}
17 changes: 17 additions & 0 deletions WebApiAuthenticationJWT/Services/UserManagementService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApiAuthenticationJWT.Services.Interfaces;

namespace WebApiAuthenticationJWT.Services
{
public class UserManagementService : IUserManagementService
{
//Todo: Dependency injection of IUserManagementRepository
public bool IsValidUser(string userName, string password)
{
return true;
}
}
}
38 changes: 35 additions & 3 deletions WebApiAuthenticationJWT/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using WebApiAuthenticationJWT.Models;
using System.Text;
using WebApiAuthenticationJWT.Services.Interfaces;
using WebApiAuthenticationJWT.Services;

namespace WebApiAuthenticationJWT
{
Expand All @@ -22,13 +28,38 @@ public Startup(IConfiguration configuration)

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

services.Configure<TokenManagement>(Configuration.GetSection("tokenManagement"));
var token = Configuration.GetSection("tokenManagement").Get<TokenManagement>();
var secret = Encoding.ASCII.GetBytes(token.Secret);

services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(token.Secret)),
ValidIssuer = token.Issuer,
ValidAudience = token.Audience,
ValidateIssuer = false,
ValidateAudience = false
};
});

services.AddScoped<IAuthenticateService, TokenAuthenticationService>();
services.AddScoped<IUserManagementService, UserManagementService>();

}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
Expand All @@ -37,9 +68,10 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env)
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
app.UseAuthentication();

app.UseHttpsRedirection();
app.UseMvc();
Expand Down
3 changes: 2 additions & 1 deletion WebApiAuthenticationJWT/WebApiAuthenticationJWT.csproj
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
Expand All @@ -11,6 +11,7 @@
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.7.12" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.3" />
</ItemGroup>

</Project>
8 changes: 7 additions & 1 deletion WebApiAuthenticationJWT/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
{
{"tokenManagement": {
"secret": "asdasdasdasffgfghnhgfhjndghg",
"issuer": "mateuscosta.dev",
"audience": "WAPIJWTAudience",
"accessExpiration": 30,
"refreshExpiration": 60
},
"Logging": {
"LogLevel": {
"Default": "Debug",
Expand Down

0 comments on commit 3848266

Please sign in to comment.