Net core custom user property

2019-07-17 01:38发布

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?

2条回答
Summer. ? 凉城
2楼-- · 2019-07-17 02:09

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

查看更多
Lonely孤独者°
3楼-- · 2019-07-17 02:16

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);
}
查看更多
登录 后发表回答