Search code examples
c#asp.net-coreasp.net-identityclaims-based-identity

How to get user claims after signin through SignInManager in ASP .NET CORE Identity?


I have an ASP .NET Core 2.0 project in which I am using Microsoft's Identity framework for authentication/authorization. I have the following method that validates the user against username and password and returns claims count. The user I am trying to login is found in database but it's claims are being returned 0 here - in the database the claims do exist against the user (see the imageenter image description here).

    [HttpPost("login")]
    public async Task<object> Login([FromBody] LoginDto model)
    {
        var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, false, false);

        if (result.Succeeded)
        {
            var appUser = _signInManager.UserManager.Users.SingleOrDefault(r => r.Email == model.Email);
            var userClaims = await _signInManager.UserManager.GetClaimsAsync(appUser); // this is returning 0 claims

            return Ok(HttpContext.User.Claims.Count());
        }

       throw new ApplicationException("INVALID_LOGIN_ATTEMPT");
    }

The answers on the possible duplicate question did not solve my problem.


Solution

  • For UserManager.GetClaimsAsync, it will query claims from AspNetUserClaims instead of AspNetUserRoles. You could check this by GetClaimsAsync

    return await UserClaims.Where(uc => uc.UserId.Equals(user.Id)).Select(c => c.ToClaim()).ToListAsync(cancellationToken);
    

    In general, we could try HttpContext.User.Claims to retrive the claims for the user, but it will work for sub-request instead of current login request. If you move this HttpContext.User.Claims to Home Index action, it will return the expected result.

    For getting claims in Login, I suggest you try

                    var claimsPrincipal = await _signInManager.CreateUserPrincipalAsync(appUser);
                    var claims = claimsPrincipal.Claims.ToList();