60 lines
2.1 KiB
C#
60 lines
2.1 KiB
C#
using Microsoft.IdentityModel.Tokens;
|
|
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Text;
|
|
|
|
namespace LogisticsApp.Server.Middleware
|
|
{
|
|
public class JwtMiddleware
|
|
{
|
|
private readonly RequestDelegate _next;
|
|
private readonly IConfiguration _configuration;
|
|
|
|
public JwtMiddleware(RequestDelegate next, IConfiguration configuration)
|
|
{
|
|
_next = next;
|
|
_configuration = configuration;
|
|
}
|
|
|
|
public async Task Invoke(HttpContext context)
|
|
{
|
|
var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last()
|
|
?? context.Request.Cookies["auth_token"];
|
|
|
|
if (token != null)
|
|
{
|
|
AttachUserToContext(context, token);
|
|
}
|
|
|
|
await _next(context);
|
|
}
|
|
|
|
private void AttachUserToContext(HttpContext context, string token)
|
|
{
|
|
try
|
|
{
|
|
var tokenHandler = new JwtSecurityTokenHandler();
|
|
var key = Encoding.UTF8.GetBytes(_configuration["Jwt:Key"] ?? throw new InvalidOperationException("JWT Key not configured"));
|
|
|
|
tokenHandler.ValidateToken(token, new TokenValidationParameters
|
|
{
|
|
ValidateIssuerSigningKey = true,
|
|
IssuerSigningKey = new SymmetricSecurityKey(key),
|
|
ValidateIssuer = true,
|
|
ValidateAudience = true,
|
|
ValidIssuer = _configuration["Jwt:Issuer"],
|
|
ValidAudience = _configuration["Jwt:Audience"],
|
|
ClockSkew = TimeSpan.Zero
|
|
}, out SecurityToken validatedToken);
|
|
|
|
var jwtToken = (JwtSecurityToken)validatedToken;
|
|
var userId = int.Parse(jwtToken.Claims.First(x => x.Type == "nameid").Value);
|
|
|
|
|
|
context.Items["UserId"] = userId;
|
|
context.Items["User"] = jwtToken.Claims.First(x => x.Type == "name").Value;
|
|
context.Items["Role"] = jwtToken.Claims.First(x => x.Type == "role").Value;
|
|
}
|
|
catch { }
|
|
}
|
|
}
|
|
} |