System.InvalidOperationException:未找到名为:“Admin”的 AuthorizationPolicy

问题描述 投票:0回答:1

我面临这个问题:

System.InvalidOperationException: The AuthorizationPolicy named: 'Admin' was not found.

但是我在 Startup.cs 中有这个:

services.AddAuthorization(options =>
{
    options.AddPolicy("Admin", policy => policy.RequireAssertion(httpCtx =>
    {
        if (httpCtx.User.HasClaim(c => c.Type == "RoleName" && c.Value.Contains("Admin")) &&
            httpCtx.User.HasClaim(c => c.Type == "StatusName" && c.Value.Contains("Active")))
            return true;
        else
            return false;
    }));

    options.AddPolicy("Worker", policy => policy.RequireAssertion(httpCtx =>
    {
        if (httpCtx.User.HasClaim(c => c.Type == "RoleName" && c.Value.Contains("Worker")) &&
            httpCtx.User.HasClaim(c => c.Type == "StatusName" && c.Value.Contains("Active")))
            return true;
        else
            return false;
    }));
});

我正在 RoleController 上测试它:

[Route("api/[controller]")]
[ApiController]
[Authorize(Policy = "Admin")]
public class RoleController : ControllerBase
{
    private readonly IRoleService _roleService;

    public RoleController(IRoleService roleService)
    {
        _roleService = roleService;
    }

从重要信息来看,token 已正确生成,以下是它的声明:

var claims = new[] {
    new Claim(JwtRegisteredClaimNames.Sub, _configuration["Jwt:Subject"]),
    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
    new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString()),
    new Claim("MemId", member.MemId.ToString()),
    new Claim("RoleName", member.RoleName),
    new Claim("StatusName", member.StatusName),
    new Claim("Email", member.Email)
};
c# .net authentication jwt authorization
1个回答
0
投票

根据错误,我们可以理解,您的应用程序中未正确注册或引用保单名称。 一旦验证您的 Startup.cs 文件中的 AddAuthorization 方法是否正确注册了“Admin”策略。

© www.soinside.com 2019 - 2024. All rights reserved.