3

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?

D.L.
  • 201
  • 6
  • 14

2 Answers2

1

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


    //...
Fei Han
  • 26,415
  • 1
  • 30
  • 41
  • Thank you. I think this should be the accepted answer, but maybe you should specify that you have to implement properly AddClaimAsync – D.L. Aug 07 '20 at 06:46
  • Does the `_signInManager.PasswordSignInAsync` by default add any additional claims? – variable Jan 10 '22 at 11:10
0

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.

  • Thank you. I was trying to do something similar, but i don't understand where claims should be passed. After adding the role claim, how should I use the claims object? – D.L. Aug 06 '20 at 12:44