Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.Net Core Identity - simple Authorization without Roles table

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?

like image 962
D.L. Avatar asked Mar 01 '26 14:03

D.L.


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


    //...
like image 120
Fei Han Avatar answered Mar 03 '26 09:03

Fei Han



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!