58 lines
No EOL
2 KiB
C#
58 lines
No EOL
2 KiB
C#
using Microsoft.IdentityModel.Tokens;
|
|
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Security.Claims;
|
|
using System.Text;
|
|
|
|
namespace iFileProxy.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 InvokeAsync(HttpContext context)
|
|
{
|
|
var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
|
|
|
|
if (token != null)
|
|
await AttachUserToContext(context, token);
|
|
|
|
await _next(context);
|
|
}
|
|
|
|
private async Task AttachUserToContext(HttpContext context, string token)
|
|
{
|
|
try
|
|
{
|
|
var tokenHandler = new JwtSecurityTokenHandler();
|
|
var key = Encoding.ASCII.GetBytes(_configuration["Jwt:Key"]);
|
|
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 = jwtToken.Claims.First(x => x.Type == ClaimTypes.NameIdentifier).Value;
|
|
|
|
// 将用户信息附加到上下文中
|
|
context.Items["User"] = userId;
|
|
}
|
|
catch
|
|
{
|
|
// 令牌验证失败,不附加用户信息
|
|
}
|
|
}
|
|
}
|
|
} |