在IdentityServer4中禁止使用授权过滤器

Moh*_*hin 3 c# authentication authorization asp.net-core identityserver4

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

AuthenticationScheme:禁止持票人.

我的用户有这样的主张: 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));
        });
Run Code Online (Sandbox Code Playgroud)

并在Configure方法中:

   app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions()
        {
            Authority = "http://localhost:5000",
            ScopeName = "openid",
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
            RequireHttpsMetadata = false,
        });
Run Code Online (Sandbox Code Playgroud)

调试输出:

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.
Run Code Online (Sandbox Code Playgroud)

我在配置中错过了什么?

PS:我已经检查过这个 SO帖子但没有成功.

lea*_*ege 10

我终于找到了时间来写出角色检查在索赔领域如何运作的内部结构:

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

简而言之 - 确保您用于角色的声明类型与您的ClaimsIdentity上的RoleClaimType匹配.或更换RequireRoleRequireClaim你的策略和正确的类型.