Asp.Net Core Identity - simple Authorization without Roles table

Viewed 762

I'm trying to develop a simple user authorization mechanism for my application, without using a specific Roles table.

The User entity has a simple Role enum property, and I would like to properly decorate the Authorize attribute on some controllers.

Maybe I'm missing something here, but how can I let the framework know what is the role of the user when or immediately after he logs in

var result = await _signInManager.PasswordSignInAsync(usr, pwd, false, lockoutOnFailure: false);

and then use the Authorize attribute?

2 Answers

The UserManager.AddClaimAsync(TUser, Claim) method could help add the specified claim to the user, you can try the following code snippet to achieve your requirement.

var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: true);

if (result.Succeeded)
{
    var user = await _userManager.FindByNameAsync(Input.Email);

    var userRole = CustomMethod_FindUserRole(Input.Email);

    await _userManager.AddClaimAsync(user, new Claim(ClaimTypes.Role, userRole));

    //...

    await _signInManager.RefreshSignInAsync(user);


    //...

You can add claim of Role to particular user using ProfileService of identity server. where you need to add

claims.Add(new Claim("Role","Admin"));

Also you need to implement policy in your starup.cs as

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

And on your action method or controller you need to put decorator as

[Authorize(Policy = "AdminCheck")]
public class VacationController : Controller
{
    public ActionResult VacationBalance()
    {
    }
}

That's it.

Related