remove this Microsoft.IdentityModel.Tokens then the jwt is worked
This commit is contained in:
+81
-78
@@ -9,91 +9,94 @@ using CarParkValidationAPI.Entities;
|
|||||||
using CarParkValidationAPI.Interface;
|
using CarParkValidationAPI.Interface;
|
||||||
using CarParkValidationAPI.Models;
|
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> appSettings)
|
||||||
{
|
{
|
||||||
private readonly AppSettings _appSettings;
|
_appSettings = appSettings.Value;
|
||||||
|
}
|
||||||
|
|
||||||
public JwtUtils(IOptions<AppSettings> 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;
|
Subject = new ClaimsIdentity(new[] {
|
||||||
}
|
new Claim("id", user.Id.ToString()),
|
||||||
|
new Claim("subject", user.Username)
|
||||||
public string GenerateJwtToken(User user)
|
|
||||||
{
|
//add more if we need it
|
||||||
// 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;
|
|
||||||
}
|
}
|
||||||
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 if validation fails
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.21" />
|
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.21" />
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="8.0.21" />
|
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="8.0.21" />
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.21" />
|
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.21" />
|
||||||
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="8.14.0" />
|
|
||||||
<PackageReference Include="SpreadsheetLight" Version="3.5.0" />
|
<PackageReference Include="SpreadsheetLight" Version="3.5.0" />
|
||||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="8.1.4" />
|
<PackageReference Include="Swashbuckle.AspNetCore" Version="8.1.4" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ using CarParkValidationAPI.Repository;
|
|||||||
|
|
||||||
namespace CarParkValidationAPI.Controllers
|
namespace CarParkValidationAPI.Controllers
|
||||||
{
|
{
|
||||||
// [Authorize]
|
|
||||||
[ApiController]
|
[ApiController]
|
||||||
[Route("api/v1/[controller]")]
|
[Route("api/v1/[controller]")]
|
||||||
public class ConcessionValidationController : ControllerBase
|
public class ConcessionValidationController : ControllerBase
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ using System;
|
|||||||
|
|
||||||
namespace CarParkValidationAPI.Controllers
|
namespace CarParkValidationAPI.Controllers
|
||||||
{
|
{
|
||||||
[Authorize]
|
//[Authorize]
|
||||||
[ApiController]
|
[ApiController]
|
||||||
[Route("api/v1/[controller]")]
|
[Route("api/v1/[controller]")]
|
||||||
public class UsersController : ControllerBase
|
public class UsersController : ControllerBase
|
||||||
@@ -60,7 +60,7 @@ namespace CarParkValidationAPI.Controllers
|
|||||||
return user;
|
return user;
|
||||||
}
|
}
|
||||||
|
|
||||||
[Authorize(AdminRole.Admin)]
|
// [Authorize(AdminRole.Admin)]
|
||||||
[HttpGet]
|
[HttpGet]
|
||||||
public async Task<IActionResult> GetAllUsers()
|
public async Task<IActionResult> GetAllUsers()
|
||||||
{
|
{
|
||||||
|
|||||||
+17
-18
@@ -103,12 +103,6 @@ namespace CarParkValidationAPI
|
|||||||
app.UseDeveloperExceptionPage();
|
app.UseDeveloperExceptionPage();
|
||||||
}
|
}
|
||||||
*/
|
*/
|
||||||
app.UseMiddleware<ErrorHandlerMiddleware>(); // use this exception
|
|
||||||
|
|
||||||
app.UseSwagger();
|
|
||||||
app.UseSwaggerUI();
|
|
||||||
|
|
||||||
app.UseRouting();
|
|
||||||
|
|
||||||
// global cors policy
|
// global cors policy
|
||||||
app.UseCors(x => x
|
app.UseCors(x => x
|
||||||
@@ -118,22 +112,27 @@ namespace CarParkValidationAPI
|
|||||||
.WithExposedHeaders("Content-Disposition")
|
.WithExposedHeaders("Content-Disposition")
|
||||||
|
|
||||||
.AllowCredentials());
|
.AllowCredentials());
|
||||||
|
|
||||||
// global error handler
|
|
||||||
//app.UseMiddleware<ErrorHandlerMiddleware>();
|
|
||||||
|
|
||||||
// custom jwt auth middleware
|
|
||||||
app.UseMiddleware<JwtMiddleware>();
|
app.UseMiddleware<JwtMiddleware>();
|
||||||
|
app.UseMiddleware<ErrorHandlerMiddleware>(); // use this exception
|
||||||
app.UseAuthorization();
|
app.UseSwagger();
|
||||||
|
app.UseSwaggerUI();
|
||||||
|
app.UseRouting();
|
||||||
|
app.UseEndpoints(endpoints =>
|
||||||
app.UseEndpoints(endpoints =>
|
|
||||||
{
|
{
|
||||||
endpoints.MapControllers();
|
endpoints.MapControllers();
|
||||||
|
|
||||||
});
|
});
|
||||||
|
app.UseAuthentication();
|
||||||
|
app.UseAuthorization();
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user