Why is ASP.NET Core Identity 2.0 Authorize filter causing me to get a 404?

后端 未结 2 695
悲&欢浪女
悲&欢浪女 2021-01-13 10:56

I have a controller that I want to restrict only to a specific role, let\'s say admin. After setting a user with the admin role, I can validate tha

2条回答
  •  北海茫月
    2021-01-13 11:24

    I think that what you need is to check claims, not roles. Add an AuthorizeAttribute such as:

    [Authorize(Policy = "AdminOnly")]
    

    And then configure a policy that requires a claim:

    services.AddAuthorization(options =>
    {
        options.AddPolicy("AdminOnly", policy =>
                          policy.RequireClaim(OpenIdConnectConstants.Claims.Role, "Admin"));
    });
    

    Or, for debugging purposes or more advanced validation, you could have:

    services.AddAuthorization(options =>
    {
        options.AddPolicy("AdminOnly", policy =>
                          policy.RequireAssertion(ctx =>
       {
           //do your checks
           return true;
       }));
    });
    

提交回复
热议问题