diff --git a/Authorization/JwtUtils.cs b/Authorization/JwtUtils.cs index 842140b..5bc3cae 100644 --- a/Authorization/JwtUtils.cs +++ b/Authorization/JwtUtils.cs @@ -9,91 +9,94 @@ using CarParkValidationAPI.Entities; using CarParkValidationAPI.Interface; using CarParkValidationAPI.Models; -namespace CarParkValidationAPI.Authorization +namespace CarParkValidationAPI.Authorization; + +public class JwtUtils : IJwtUtils { - + private readonly AppSettings _appSettings; - public class JwtUtils : IJwtUtils + public JwtUtils(IOptions appSettings) { - private readonly AppSettings _appSettings; + _appSettings = appSettings.Value; + } - public JwtUtils(IOptions appSettings) + public string GenerateJwtToken(User user) + { + // generate token that is valid for 2 days + var tokenHandler = new JwtSecurityTokenHandler(); + var key = Encoding.ASCII.GetBytes(_appSettings.Secret); + var tokenDescriptor = new SecurityTokenDescriptor { - _appSettings = appSettings.Value; - } - - public string GenerateJwtToken(User user) - { - // generate token that is valid for 2 days - var tokenHandler = new JwtSecurityTokenHandler(); - var key = Encoding.ASCII.GetBytes(_appSettings.Secret); - var tokenDescriptor = new SecurityTokenDescriptor - { - Subject = new ClaimsIdentity(new[] { - new Claim("id", user.Id.ToString()), - new Claim("subject", user.Username) - - //add more if we need it - } - ), - Expires = DateTime.UtcNow.AddDays(2), - SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) - }; - var token = tokenHandler.CreateToken(tokenDescriptor); - return tokenHandler.WriteToken(token); - } - // get back id and username. in subject - public User? ValidateJwtToken(string token) - { - if (token == null) - return null; - - var tokenHandler = new JwtSecurityTokenHandler(); - var key = Encoding.ASCII.GetBytes(_appSettings.Secret); - try - { - tokenHandler.ValidateToken(token, new TokenValidationParameters - { - ValidateIssuerSigningKey = true, - IssuerSigningKey = new SymmetricSecurityKey(key), - ValidateIssuer = false, - ValidateAudience = false, - // set clockskew to zero so tokens expire exactly at token expiration time (instead of 5 minutes later) - ClockSkew = TimeSpan.Zero - }, out SecurityToken validatedToken); - - var jwtToken = (JwtSecurityToken)validatedToken; - // var userId = int.Parse(jwtToken.Claims.First(x => x.Type == "id").Value); //old - int userId = 0; - string username = ""; - Claim claim; - for (int i = 0; i< jwtToken.Claims.Count(); i++) - { - claim = jwtToken.Claims.ElementAt(i); - if (claim.Type == "id") - { - userId = int.Parse(claim.Value); - } - else if (claim.Type == "subject") - { - username = claim.Value; - } - - if (!string.IsNullOrEmpty(username) && userId > 0) - { - break; - } - } - - User user = new User(); - user.Id = userId; - user.Username = username; - - // return user id from JWT token if validation successful - return user; + Subject = new ClaimsIdentity(new[] { + new Claim("id", user.Id.ToString()), + new Claim("subject", user.Username) + + //add more if we need it } - catch + ), + Expires = DateTime.UtcNow.AddDays(2), + + SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) + }; + var token = tokenHandler.CreateToken(tokenDescriptor); + return tokenHandler.WriteToken(token); + } + // get back id and username. in subject + public User? ValidateJwtToken(string token) + { + if (token == null) + return null; + + var tokenHandler = new JwtSecurityTokenHandler(); + var key = Encoding.ASCII.GetBytes(_appSettings.Secret); + try + { + tokenHandler.ValidateToken(token, new TokenValidationParameters { + ValidateIssuerSigningKey = true, + IssuerSigningKey = new SymmetricSecurityKey(key), + ValidateIssuer = false, + ValidateLifetime = true, + ValidateAudience = false, + // set clockskew to zero so tokens expire exactly at token expiration time (instead of 5 minutes later) + // ClockSkew = TimeSpan.Zero + ClockSkew = TimeSpan.FromDays(2), + }, out SecurityToken validatedToken); + + var jwtToken = (JwtSecurityToken)validatedToken; + // var userId = int.Parse(jwtToken.Claims.First(x => x.Type == "id").Value); //old + int userId = 0; + string username = ""; + Claim claim; + for (int i = 0; i < jwtToken.Claims.Count(); i++) + { + claim = jwtToken.Claims.ElementAt(i); + if (claim.Type == "id") + { + userId = int.Parse(claim.Value); + } + else if (claim.Type == "subject") + { + username = claim.Value; + } + + if (!string.IsNullOrEmpty(username) && userId > 0) + { + break; + } + } + + User user = new User(); + user.Id = userId; + user.Username = username; + + // return user id from JWT token if validation successful + return user; + } + catch (Exception ex) + { + { + Console.WriteLine(ex.ToString()); // return null if validation fails return null; } diff --git a/CarParkValidationAPI.csproj b/CarParkValidationAPI.csproj index 4f8186f..2d21a70 100644 --- a/CarParkValidationAPI.csproj +++ b/CarParkValidationAPI.csproj @@ -10,7 +10,7 @@ - + diff --git a/Controllers/ConcessionValidationController.cs b/Controllers/ConcessionValidationController.cs index c3468eb..b49cec2 100644 --- a/Controllers/ConcessionValidationController.cs +++ b/Controllers/ConcessionValidationController.cs @@ -10,7 +10,7 @@ using CarParkValidationAPI.Repository; namespace CarParkValidationAPI.Controllers { - // [Authorize] + [ApiController] [Route("api/v1/[controller]")] public class ConcessionValidationController : ControllerBase diff --git a/Controllers/UsersController.cs b/Controllers/UsersController.cs index 6d7dae1..16cd1d0 100644 --- a/Controllers/UsersController.cs +++ b/Controllers/UsersController.cs @@ -9,7 +9,7 @@ using System; namespace CarParkValidationAPI.Controllers { - [Authorize] + //[Authorize] [ApiController] [Route("api/v1/[controller]")] public class UsersController : ControllerBase @@ -60,7 +60,7 @@ namespace CarParkValidationAPI.Controllers return user; } - [Authorize(AdminRole.Admin)] + // [Authorize(AdminRole.Admin)] [HttpGet] public async Task GetAllUsers() { diff --git a/Startup.cs b/Startup.cs index 421abb1..f8533ea 100644 --- a/Startup.cs +++ b/Startup.cs @@ -103,12 +103,6 @@ namespace CarParkValidationAPI app.UseDeveloperExceptionPage(); } */ - app.UseMiddleware(); // use this exception - - app.UseSwagger(); - app.UseSwaggerUI(); - - app.UseRouting(); // global cors policy app.UseCors(x => x @@ -118,22 +112,27 @@ namespace CarParkValidationAPI .WithExposedHeaders("Content-Disposition") .AllowCredentials()); - - // global error handler - //app.UseMiddleware(); - - // custom jwt auth middleware app.UseMiddleware(); - - app.UseAuthorization(); - - - - app.UseEndpoints(endpoints => + app.UseMiddleware(); // use this exception + app.UseSwagger(); + app.UseSwaggerUI(); + app.UseRouting(); + app.UseEndpoints(endpoints => { endpoints.MapControllers(); - + }); + app.UseAuthentication(); + app.UseAuthorization(); + + + + + + + + + } }