ASP.NET Core Authorization: 跳过JWT校验

本文记录了如何在asp.net core 9.0上为WebApi配置跳过JWT校验的方法。

项目准备

执行以下命令

dotnet new webapi --use-minimal-apis --name MockJwtTestApi --output MockJwtTestApi --auth None
dotnet add package Swashbuckle.AspNetCore --project MockJwtTestApi
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer --project MockJwtTestApiy以

以创建名为MockJwtTestApi的WebApi项目。

核心实现

编辑MockJwtTestApi\Program.cs,使之内容为

 1 using Microsoft.OpenApi.Models;
 2 
 3 
 4 (OpenApiSecurityScheme Scheme, OpenApiSecurityRequirement Requirement) jwtSchemeA =
 5 (
 6     Scheme: new OpenApiSecurityScheme 
 7     { 
 8         In = ParameterLocation.Header, 
 9         Type = SecuritySchemeType.Http, 
10         Scheme = Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerDefaults.AuthenticationScheme 
11     },
12 
13     Requirement: new OpenApiSecurityRequirement
14     {
15         [new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = nameof(jwtSchemeA) } }] = Array.Empty<string>()
16     }
17 );
18 
19 var builder = WebApplication.CreateBuilder(args);
20 builder.Services.AddSwaggerGen((option) =>
21 {
22     option.AddSecurityDefinition(nameof(jwtSchemeA), jwtSchemeA.Scheme);
23 });
24 
25 builder.Services.AddOpenApi();
26 
27 builder.Services.AddAuthorization();
28 builder.Services.AddAuthentication()
29     .AddJwtBearer(nameof(jwtSchemeA), options =>
30     {
31         options.TokenValidationParameters = new()
32         {
33             ValidateAudience = false,
34             ValidateIssuer = false,
35             ValidateIssuerSigningKey = false,
36             ValidateLifetime = false,
37             SignatureValidator = (token, p) => new Microsoft.IdentityModel.JsonWebTokens.JsonWebToken(token)
38         };
39 
40         // Do not map "sub", "scp" to the according Microsoft's qualified name specified in System.Security.Claims.ClaimTypes.
41         options.MapInboundClaims = false;
42     });
43 
44 var app = builder.Build();
45 
46 // Configure the HTTP request pipeline.
47 if (app.Environment.IsDevelopment())
48 {
49     app.MapOpenApi();
50 
51     app.UseSwagger();
52     app.UseSwaggerUI();
53 }
54 
55 app.UseHttpsRedirection();
56 
57 app.UseAuthentication();
58 app.UseAuthorization();
59 
60 app.MapGet("/AuthorizedUser", (HttpContext httpContext) =>
61 {
62     return new
63     {
64         IsAuthenticated = httpContext.User.Identity.IsAuthenticated,
65         Claims = httpContext.User.Claims?.Select(c => new { c.Type, c.Value }).ToArray()
66     };
67 })
68 .WithOpenApi((operation) =>
69 {
70     operation.Security = [jwtSchemeA.Requirement];
71 
72     return operation;
73 });
74 
75 app.MapGet("/PublicAccess", (HttpContext httpContext) =>
76 {
77     return new
78     {
79         IsAuthenticated = httpContext.User.Identity.IsAuthenticated,
80         Claims = httpContext.User.Claims?.Select(c => new { c.Type, c.Value }).ToArray()
81     };
82 });
83 
84 await app.RunAsync();

 

实现跳过JWT签名校验的关键是第37行。注意这里不能用new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(token)为返回值,否则会失败——在AddJwtBearer扩展方法里,为JwtBearerOptions对象的Events属性配上OnAuthenticationFailed事件

options.Events = new()
{
   OnAuthenticationFailed = context => Console.WriteLine(context.Exception.Message); 
};

将可以看到如下异常信息:

IDX10506: Signature validation failed. The user defined 'Delegate' specified on TokenValidationParameters did not return a 'Microsoft.IdentityModel.JsonWebTokens.JsonWebToken', but returned a 'System.IdentityModel.Tokens.Jwt.JwtSecurityToken' when validating token: '[PII of type 'Microsoft.IdentityModel.JsonWebTokens.JsonWebToken' is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'. If you are using ASP.NET Core 8 or later, see https://learn.microsoft.com/en-us/dotnet/core/compatibility/aspnet-core/8.0/securitytoken-events for more details.

 

参考资料:

[1] "Add an authorization header to your swagger-ui with Swashbuckle (revisited)", https://mattfrear.com/2018/07/21/add-an-authorization-header-to-your-swagger-ui-with-swashbuckle-revisited/
[2] "ASP.NET Core 同时支持多种认证方式 | Swagger 支持", https://blog.csdn.net/mzl87/article/details/126605540
[3] "ASP.NET Core 同时支持多种认证方式", https://blog.csdn.net/mzl87/article/details/126605384
[4] "ASP.NET Core 实现自定义认证", https://blog.csdn.net/mzl87/article/details/123823581
[5] ".Net 6 Minimal Api Authentication (JWT) with Swagger and Open API", https://dev.to/moe23/net-6-minimal-api-authentication-jwt-with-swagger-and-open-api-2chh
[6] ".NET 6 WebApi Swagger 配置 JWT token+Authorize认证", https://blog.csdn.net/qq_61596453/article/details/136416534

posted @ 2025-11-11 21:06  OfAllTheIdiots  阅读(16)  评论(0)    收藏  举报