当前位置: 首页 > news >正文

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

http://www.jsqmd.com/news/37852/

相关文章:

  • 学习昇腾硬件软件产品名称
  • 实用指南:[linux仓库]信号保存[进程信号肆]
  • v4l2_subdev和video_device区分
  • 第七天 设计用例方法
  • AT_agc034_c [AGC034C] Tests
  • 论安慰人
  • 电商运营每天在忙啥?拆解4个核心工作,新手也能照做 - 智慧园区
  • 102302112王光诚作业2
  • 详细介绍:LLaMA-Factory实战优化进阶
  • ch3题解
  • 2025年11月全日制艺考生文化课新推荐:聚焦全日制艺考生文化课培训/全日制艺考生文化课机构/核心考点攻坚与沉浸式教学
  • 2025年11月镀锌板品牌新榜:聚焦HC300DPD+Z镀锌板//镀锌花纹板/热镀锌花纹板/Q345B镀锌花纹板全产业链优势!
  • [随笔]关于意识形态
  • Luogu P4151 [WC2011] 最大XOR和路径 题解
  • 2025年11月磨床电主轴厂家新推荐:聚焦国产磨床主轴/进口磨床主轴/内圆磨床主轴/外圆磨床主轴测评!
  • 会员小程序
  • ff
  • MySQL学习,详解分页查询(limit)
  • 英语_阅读_A new way to see the world:AR_待读
  • 2025年11月腻子粉厂家新推荐榜:聚焦环保腻子粉/植物腻子粉/净醛腻子粉/健康腻子粉/无味腻子粉环保性能深度解析!
  • 深入解析:嵌入式软件架构--按键消息队列2(组合键,按键转义与三种消息模式)
  • 2025聚脲涂料行业优质厂家推荐榜:宁国创遂领衔,手工 / 喷涂 / 天冬聚脲涂料实力派齐聚
  • 2025优质弯管厂家推荐榜:合肥翼达机械五星领跑,安徽企业助力产业升级
  • Redisson源码剖析-可重试机制的实现
  • 2025发泡混凝土优质厂家推荐榜:云南锦乐五星领跑,西南三家企业凭特色实力入围
  • 2025篷房行业优选榜:华烨海特斯五星领跑 铝合金 / 装配式 / 工业篷房领域 4 家实力企业精准适配多场景
  • 2025浸没式/液冷超充/新能源车/超充站领域实力厂家排行榜:中碳创新领衔,四大品牌重塑新能源车补能生态
  • 2025国内AI获客公司排行榜:全平台精准破局,4 家企业领跑抖音/快手/小红书获客赛道
  • HNOI2016 序列
  • 2025年山东画室机构实力推荐:济南大道画室领跑美术艺考培训新标准