当前位置: 首页 > 编程语言 > C#

ASP.NETCoreIdentity2.0授权过滤器为什么会导致我得到404?

时间:2023-04-11 02:58:32 C#

为什么ASP.NETCoreIdentity2.0授权过滤器导致我得到404?我有一个控制器,我只想将其限制为特定角色,比方说管理员。为用户设置管理员角色后,我可以使用IsInRoleAsync方法(返回true)验证他是否在该角色中。使用[Authorize(Roles="admin")]设置属性时,同一用户收到404。我正在使用不记名令牌(我认为这不相关,但无论如何),这就是我要调试的内容:控制器没有[Authorize]:ReturnResource。[OK]Controllerwith[Authorize]:只有当我使用Authentication:Bearer[accesstoken]Authentication:Bearer[accesstoken][OK]Controllerwith[Authorize(Roles="admin")]:即使我也使用设置了角色的用户登录后得到404[NOK]我不知道我是否缺少某些配置,但这是我的ConfigureServices:publicvoidConfigureServices(IServiceCollectionservices){services.AddMvc();//添加框架services.services.AddDbContext(options=>{options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));options.UseOpenIddict();});services.AddIdentity().AddEntityFrameworkStores().AddDefaultTokenProviders();services.AddOpenIddict(opt=>{opt.AddEntityFrameworkCoreStores();opt.AddMvcBinders();opt.EnableTokenEndpoint("/api/token");opt.AllowPasswordFlow();opt.DisableHttpsRequirement();//仅供开发人员使用!opt.UseJsonWebTokens();opt.AddEphemeralSigningKey();opt.AllowRefreshTokenFlow();opt.SetAccessTokenLifetime(TimeSpan.FromMinutes(5));});services.AddAuthentication(options=>{options.DefaultScheme=OAuthValidationDefaults.AuthenticationScheme;options.DefaultAuthenticateScheme=OAuthValidationConstants.Schemes.Bearer;options.DefaultSignInScheme=IdentityConstants.ExternalScheme;}).AddJwtBearer(options=>{options.Authority="http://localhost:44337/";options.Audience="resource_server";options.RequireHttpsMetadata=false;options.TokenValidationParameters=newTokenValidationParameters{NameClaimType=OpenIdConnectConstants.Claims.Subject,RoleClaimType=OpenIdConnectConstants.Claims.Role};});services.Configure(options=>{//密码设置options.Password.RequireDigit=true;options.Password.RequiredLength=8;options.Password.RequireNonAlphanumeric=false;options.Password.RequireUppercase=true;options.Password.RequireLowercase=false;//锁定设置options.Lockout.DefaultLockoutTimeSpan=TimeSpan.FromMinutes(30);options.Lockout.MaxFailedAccessAttempts=10;//用户设置options.User.Require独特的电子邮件=真;//添加应用程序services.options.ClaimsIdentity.UserNameClaimType=OpenIdConnectConstants.Claims.Name;options.ClaimsIdentity.UserIdClaimType=OpenIdConnectConstants.Claims.Subject;options.ClaimsIdentity.RoleClaimType=OpenIdConnectConstants.Claims.Role;}.AddSingleton(typeof(RoleManager));//添加应用程序services.services.AddTransient();服务.AddTransient();您可能会收到404响应,因为Identity-自动配置为服务的默认身份验证、登录/注销和质询/拒绝场景服务。AddIdentity()-尝试将您重定向到“拒绝访问页面”(默认情况下为Account/AccessDenied),它可能在您的应用程序中不存在尝试覆盖默认的挑战/禁止方案,看看它是否解决了您的问题:services.AddAuthentication(options=>{//...options.DefaultChallengeScheme=JwtBearerDefaults.AuthenticationScheme;options.DefaultForbidScheme=JwtBearerDefaults.AuthenticationScheme;});第二个问题,请确保您已禁用JWT声明映射功能。如果不是,当您将JWT处理程序配置为使用角色作为ClaimsPrincipal.IsInRole(...)ClaimsPrincipal.IsInRole(...)(RoleClaimType=OpenIdConnectConstants.Claims.Role)。services.AddAuthentication(options=>{options.DefaultScheme=JwtBearerDefaults.AuthenticationScheme;}).AddJwtBearer(options=>{//...options.SecurityTokenValidators.Clear();options.SecurityTokenValidators.Add(newJwtSecurityTokenHandler{//禁用内置的JWT声明映射功能。InboundClaimTypeMap=newDictionary()});});我认为您需要的是检查声明,而不是角色。添加AuthorizeAttribute例如:[Authorize(Policy="AdminOnly")]然后配置需要声明的policy:services.AddAuthorization(options=>{options.AddPolicy("AdminOnly",policy=>policy.RequireClaim(OpenIdConnectConstants.Claims.Role,"Admin"));});或者,出于调试目的或更高级的验证,您可以:如果分享的所有内容对您都有用,并且您需要了解更多C#学习教程,希望您多加关注——services.AddAuthorization(options=>{options.AddPolicy("AdminOnly",policy=>policy.RequireAssertion(ctx=>{//你的检查是否返回true;}));});本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: