Cookie授权仅对脚手架Identity区域生效,如何兼容JWT与Cookie授权?
解决方案
你遇到的问题根源是调用AddIdentityServerJwt后,默认认证方案被覆盖为了IdentityServerJwt组合方案,导致自定义Razor页面不会优先解析Cookie身份信息,按以下步骤修改配置即可实现需求:
1. 显式指定默认认证方案为Cookie
修改ConfigureServices中的认证配置,把默认的认证、质询方案指定为Identity自带的Cookie方案:
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.ApiAuthorization.IdentityServer; // ... 其他代码 services.AddAuthentication(options => { // 全局默认使用Cookie认证,自动解析Cookie填充用户Claims options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme; options.DefaultChallengeScheme = IdentityConstants.ApplicationScheme; }) .AddIdentityServerJwt();
该配置生效后,所有未显式指定认证方案的终结点,都会优先走Cookie认证逻辑:
- 已登录用户的Claims会自动填充到
HttpContext.User中,哪怕页面没有加[Authorize]特性也可以正常读取 - 未登录用户可以正常访问公开页面,不会被强制跳转登录
2. 给API接口指定JWT认证方案
为了不破坏原有的移动端JWT授权逻辑,给所有API接口单独指定JWT认证方案,推荐用全局约定的方式统一配置,无需逐个修改Controller:
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc.Authorization; // ... 其他代码 services.AddControllers(options => { // 构造JWT专属授权策略 var jwtAuthPolicy = new AuthorizationPolicyBuilder() .AddAuthenticationSchemes(IdentityServerJwtConstants.IdentityServerJwtBearerScheme) .RequireAuthenticatedUser() .Build(); // 全局应用到所有API Controller options.Filters.Add(new AuthorizeFilter(jwtAuthPolicy)); });
如果部分API接口允许匿名访问,单独给对应接口/Controller加[AllowAnonymous]特性即可。
3. 可选:Razor页面权限配置
如果需要给指定路径的Razor页面加登录要求,比如/Admin路径必须登录才能访问,直接通过Razor Pages授权约定配置即可,不需要额外指定认证方案:
services.AddRazorPages(options => { // 要求Admin路径下所有页面必须登录 options.Conventions.AuthorizeFolder("/Admin"); });
配置完成后即可删除你之前手动加在页面上的[Authorize(AuthenticationSchemes = "Identity.Application")]特性,所有逻辑都可以正常运行。
内容的提问来源于stack exchange,提问作者del
相关产品推荐
相关产品推荐

