I'm using the default authorization in my .NET Core project. I want to check if an user is admin so in ApplicationUser.cs model I've added this:
public class ApplicationUser : IdentityUser
{
public bool admin { get; set; }
}
I migrated these changes into my SQL database and I can see the 'admin' property inside the AspNetUsers table. How do I check the 'admin' property of the currently logged in user?
You can access the current user instance through the UserManager<T>
object, which can be injected into your controller as a constructor parameter. The method GetUserAsync
takes a ClaimsPrincipal
, which in this case is the User of the HttpContext
.
private readonly UserManager<ApplicationUser> _userManager;
public HomeController(UserManager<ApplicationUser> userManager) {
_userManager = userManager;
var user = _userManager.GetUserAsync(HttpContext.User);
}
I agree with the above answer by Peter to just use the user
variable and check for user.admin
, however, I strongly suggest extending your project to use a simple Role-based Authorization to simplify things in the long run. You can achieve this with the following documentation: https://docs.microsoft.com/en-us/aspnet/core/security/authorization/roles