在使用IdentityServer4教程测试AspNetAuthorization 的过程中,我添加了一个简单的[Authorize(Roles = "Administrator")],从那时起,我得到此错误:



我的用户有以下主张:new Claim(ClaimTypes.Role, "Administrator", ClaimValueTypes.String)

ConfigureServices方法中:

 services.AddAuthorization(options =>
        {
            options.AddPolicy("AdministratorOnly", policy => policy.RequireRole("Administrator"));
        });

        services.AddMvc(config =>
        {
            var policy = new AuthorizationPolicyBuilder()
                        .RequireAuthenticatedUser()
                        .Build();

            config.Filters.Add(new AuthorizeFilter(policy));
        });

并在Configure方法中:
   app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions()
        {
            Authority = "http://localhost:5000",
            ScopeName = "openid",
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
            RequireHttpsMetadata = false,
        });

调试输出:
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker: Debug: Executing action LearningEntityServer4.OAuth.ValuesController.Get (LearningEntityServer4.OAuth)
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService: Information: Authorization was successful for user: myuser.
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService: Information: Authorization failed for user: myuser.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker: Warning: Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
Microsoft.AspNetCore.Mvc.ChallengeResult: Information: Executing ChallengeResult with authentication schemes ().
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerMiddleware: Information: AuthenticationScheme: Bearer was forbidden.

我在配置中错过了什么?

PS:我已经检查了this SO帖子,但没有成功。

最佳答案

我终于找到了时间来撰写角色检查在 claim 环境中如何工作的内部知识:

https://leastprivilege.com/2016/08/21/why-does-my-authorize-attribute-not-work/

简而言之-确保用于角色的声明类型与ClaimsIdentity上的RoleClaimType匹配。或者在您的策略中将RequireRole替换为RequireClaim并使用正确的类型。

关于c# - IdentityServer4中的“授权”过滤器禁止承载,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39051705/

10-13 03:18