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

38 Views Asked by At

I am facing this issue:

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

But I have this in 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;
    }));
});

And I am testing it on RoleController:

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

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

From important infomations, token is generated properly and these are the claims of it:

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)
};
0

There are 0 best solutions below