diff --git a/AspNetCoreApi/AspNetCoreApi.csproj b/AspNetCoreApi/AspNetCoreApi.csproj index 281a2ce..b70a35a 100644 --- a/AspNetCoreApi/AspNetCoreApi.csproj +++ b/AspNetCoreApi/AspNetCoreApi.csproj @@ -7,6 +7,7 @@ + diff --git a/AspNetCoreApi/Controllers/AuthController.cs b/AspNetCoreApi/Controllers/AuthController.cs new file mode 100644 index 0000000..82ccdad --- /dev/null +++ b/AspNetCoreApi/Controllers/AuthController.cs @@ -0,0 +1,28 @@ +using AspNetCoreApi.Services; +using Microsoft.AspNetCore.Mvc; + +namespace AspNetCoreApi.Controllers +{ + [ApiController] + [Route("[controller]")] + public class AuthController : ControllerBase + { + private readonly JWTAuthenticationService _service; + + public AuthController(JWTAuthenticationService service) + { + _service = service; + } + + [HttpPost("authenticate")] + public async Task Authenticate(string username, string password) + { + var token = await _service.Authenticate(username, password); + if (token == null) + { + return Unauthorized(); + } + return Ok(new { Token = token }); + } + } +} diff --git a/AspNetCoreApi/Controllers/NeedAuthController.cs b/AspNetCoreApi/Controllers/NeedAuthController.cs new file mode 100644 index 0000000..c8beec0 --- /dev/null +++ b/AspNetCoreApi/Controllers/NeedAuthController.cs @@ -0,0 +1,26 @@ +using AspNetCoreApi.Models; +using AspNetCoreApi.Services; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; + +namespace AspNetCoreApi.Controllers +{ + [ApiController] + [Authorize] + [Route("[controller]")] + public class NeedAuthController : ControllerBase + { + private readonly ILogger _logger; + + public NeedAuthController(ILogger logger) + { + _logger = logger; + } + + [HttpGet(Name = "GetNeedAuth")] + public string Get() + { + return "Authorized"; + } + } +} diff --git a/AspNetCoreApi/Program.cs b/AspNetCoreApi/Program.cs index 298315c..a85224e 100644 --- a/AspNetCoreApi/Program.cs +++ b/AspNetCoreApi/Program.cs @@ -3,8 +3,11 @@ using AspNetCoreApi.DbContexts; using AspNetCoreApi.Middlewares; using AspNetCoreApi.Models; using AspNetCoreApi.Services; +using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; +using Microsoft.IdentityModel.Tokens; +using System.Text; namespace AspNetCoreApi { @@ -32,6 +35,29 @@ namespace AspNetCoreApi .AddEntityFrameworkStores() .AddDefaultTokenProviders(); + // JWT Authorization + string jwtKey = "ThisIsMyMyJWTKey1234!ThisIsMyMyJWTKey1234!"; + builder.Services.AddAuthentication(options => + { + options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; + options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; + }) + .AddJwtBearer(options => + { + options.TokenValidationParameters = new TokenValidationParameters + { + ValidateIssuer = true, + ValidateAudience = true, + ValidateLifetime = true, + ValidateIssuerSigningKey = true, + ValidIssuer = "MyIssuer", + ValidAudience = "MyAudience", + IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)) + }; + }); + + builder.Services.AddScoped(); + // Add services to the container. builder.Services.AddControllers(); @@ -55,6 +81,7 @@ namespace AspNetCoreApi app.UseHttpsRedirection(); + app.UseAuthentication(); app.UseAuthorization(); diff --git a/AspNetCoreApi/Services/JWTAuthenticationService.cs b/AspNetCoreApi/Services/JWTAuthenticationService.cs new file mode 100644 index 0000000..1524bac --- /dev/null +++ b/AspNetCoreApi/Services/JWTAuthenticationService.cs @@ -0,0 +1,48 @@ +using AspNetCoreApi.Models; +using Microsoft.AspNetCore.Identity; +using Microsoft.IdentityModel.Tokens; +using System.IdentityModel.Tokens.Jwt; +using System.Security.Claims; +using System.Text; + +namespace AspNetCoreApi.Services +{ + public class JWTAuthenticationService + { + private readonly UserManager _userManager; + private readonly string _key = "ThisIsMyMyJWTKey1234!ThisIsMyMyJWTKey1234!"; + + + public JWTAuthenticationService(UserManager userManager) + { + _userManager = userManager; + } + + public async Task Authenticate(string username, string password) + { + var user = await _userManager.FindByNameAsync(username); + if (user == null) + return null; + + if (await _userManager.CheckPasswordAsync(user, password) == false) + return null; + + var tokenHandler = new JwtSecurityTokenHandler(); + var key = Encoding.UTF8.GetBytes(_key); + var tokenDescriptor = new SecurityTokenDescriptor + { + Subject = new ClaimsIdentity(new Claim[] + { + new Claim(ClaimTypes.Name, user.UserName), + new Claim(ClaimTypes.NameIdentifier, user.Id) + }), + Expires = DateTime.UtcNow.AddHours(0.5), + SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) + }; + + var token = tokenHandler.CreateToken(tokenDescriptor); + return tokenHandler.WriteToken(token); + + } + } +}