Asp.net core 的JWT 中间件
在ASP.NET Core中,你可以使用一个中间件来处理JWT(JSON Web Tokens)。以下是一个简单的示例,展示了如何创建一个JWT中间件来验证传入请求的JWT令牌。
首先,安装必要的NuGet包:
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
然后,创建JWT中间件:
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Text;
using System.Threading.Tasks;
public class JwtMiddleware
{
private readonly RequestDelegate _next;
public JwtMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
if (token != null)
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes("your_secret_key");
var validationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false,
// You can add more validations here
};
try
{
var claims = tokenHandler.ValidateToken(token, validationParameters, out var validatedToken);
context.Items["User"] = claims;
}
catch
{
// Token is not valid
context.Response.StatusCode = 401;
return;
}
}
else
{
// Token not found
context.Response.StatusCode = 401;
return;
}
await _next(context);
}
}
// Extension method used to add the middleware to the HTTP request pipeline.
public static class JwtMiddlewareExtensions
{
public static IApplicationBuilder UseJwtMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<JwtMiddleware>();
}
}
然后,在Startup.cs
中配置中间件:
public void Configure(IApplicationBuilder app, IWebHostEn
评论已关闭