如何在已有Identity认证的Web项目中同时启用JWT API认证?
要在已使用Identity Cookie认证的项目中同时支持JWT认证,需对现有配置做以下几处核心修改:
1. 新增JWT认证服务注册
在原有AddCookie配置之后,调用AddJwtBearer方法添加JWT认证支持,配置验证参数(密钥、签发方、受众等建议从配置文件读取,示例中为便于演示直接写死)。
2. 保留Cookie作为Web端默认方案
无需修改原有Cookie的默认配置,让Web端页面继续使用Cookie认证;API接口则通过指定认证方案来启用JWT。
3. 可选:配置通用授权策略
若需要让部分接口同时兼容两种认证方式,可定义授权策略统一管理。
修改后的完整配置代码
using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens; using System.Text; services.AddAuthentication(options => { // 保留Cookie作为Web端的默认认证/挑战方案 options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; }) // 原有Cookie认证配置 .AddCookie(options => { options.LoginPath = "/Login"; options.LogoutPath = "/Logout"; options.ExpireTimeSpan = TimeSpan.FromMinutes(43200); }) // 添加JWT认证配置 .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, // 替换为实际签发方地址 ValidIssuer = "https://your-issuer-domain.com", // 替换为实际受众地址 ValidAudience = "https://your-audience-domain.com", // 替换为实际密钥(建议从appsettings.json读取) IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-strong-secret-key-min-16-chars")) }; // 可选:支持从查询参数获取令牌(适配特殊场景) options.Events = new JwtBearerEvents { OnMessageReceived = context => { var token = context.Request.Query["access_token"]; if (!string.IsNullOrEmpty(token)) { context.Token = token; } return Task.CompletedTask; } }; }); // 可选:添加兼容两种认证方式的授权策略 services.AddAuthorization(options => { options.AddPolicy("CookieOrJwt", policy => { policy.AuthenticationSchemes.Add(CookieAuthenticationDefaults.AuthenticationScheme); policy.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme); policy.RequireAuthenticatedUser(); }); });
后续使用说明
- Web端页面:直接使用
[Authorize]特性,自动走Cookie认证流程,无需额外修改。 - API接口:指定JWT认证方案强制使用令牌验证:
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] [ApiController] [Route("api/[controller]")] public class DemoApiController : ControllerBase { // API接口逻辑 } - 兼容场景:若想让接口同时支持两种认证方式,使用自定义策略:
[Authorize(Policy = "CookieOrJwt")]
内容的提问来源于stack exchange,提问作者YA3H
相关产品推荐
相关产品推荐

