0

Please or Register to create posts and topics.

Problem with the authentication

Hi,

I've created an additional role, and now I want only one user with that role to get access to the API. So far I have added the following code.

public static class ApplicationPermissions
{
 	public static ApplicationPermission EmployeeRoles = new ApplicationPermission("Employee Roles", "employee.view", RolesPermissionGroupName, "Permission for employees");
}

The role exists in the database and can be assigned to the user. As well as everything ok.

In the source Policies I add.

public class Policies
{
   public const string Employee = "Employee";
}

I create this class in the Authorization directory:

public class EmployeeRoleAuthorizationRequirement : IAuthorizationRequirement
{
    public class EmployeeAuthorizationHandler : AuthorizationHandler<EmployeeRoleAuthorizationRequirement, string>
    {
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, EmployeeRoleAuthorizationRequirement requirement, string roleName)
        {
            if (context.User == null)
                return Task.CompletedTask;

            if (context.User.HasClaim(ClaimConstants.Permission, ApplicationPermissions.EmployeeRoles) || context.User.IsInRole(roleName))
                context.Succeed(requirement);

            return Task.CompletedTask;
        }
    }
}

and add the startup.

services.AddAuthorization(options =>
  options.AddPolicy(Authorization.Policies.Employee, policy => policy.Requirements.Add(new EmployeeRoleAuthorizationRequirement()));

In the controller:

[Authorize(AuthenticationSchemes = IdentityServerAuthenticationDefaults.AuthenticationScheme)]
[Route("api/[controller]")]
public class BankController : Controller {}

[HttpGet("banks")]
[Produces(typeof(List<BankViewModel>))]
[Authorize(Policies.Employee)]
public IActionResult GetBanks()
{ }

When the client accesses the API, I get the error: Cannot Get Access Denied

 

I set a break point in the source EmployeeRoleAuthorizationRequirement but the HandleRequirementAsync are not called. What I make wrong?

 

Have you added to the startup class

services.AddSingleton<IAuthorizationHandler, EmployeeAuthorizationHandler>();

?

Hi Al Ve,

yes it was my error. Thanks your