在 ASP.NET Core 中,我们可以使用 Microsoft.AspNetCore.Authentication.JwtBearer 包来处理 JWT token。在使用过程中,若解码出错,会抛出 Microsoft.IdentityModel.Tokens.SecurityTokenException 异常。
为了处理这个异常,我们需要在 Startup.cs 中注册一个中间件来捕获异常并使用自定义错误返回格式。以下代码演示了如何进行异常处理:
首先,我们需要在 ConfigureServices 方法中注册 JwtBearer 服务:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = Configuration["Jwt:Issuer"], ValidAudience = Configuration["Jwt:Audience"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"])) }; });
接着,在 Configure 方法中注册 middleware:
app.UseExceptionHandler(errorApp => { errorApp.Run(async context => { context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; context.Response.ContentType = "application/json";
var jsonError = context.Features.Get();
if (jsonError != null)
{
var error = new
{
Message = "An error occurred whilst decoding the JWT token",
Exception = jsonError.Error.Message
};
var json = JsonSerializer.Serialize(error);
await context.Response.WriteAsync(json);
}
});
});
这段代码会返回一个 JSON 格式的错误信息,包含异常信息。若发生 SecurityTokenException 异常,将会返回自定义错误信息,便于我们进行跟踪和调试。
最后,在 Controller 中使用 [Authorize] 标注它,这会触发 middleware 开始为您验证 token。