本文介绍了通过ASP .NET CORE Identity中的SignInManager登录后如何获得用户声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP .NET Core 2.0项目,其中使用Microsoft的Identity框架进行身份验证/授权.我有以下方法可根据用户名和密码验证用户并返回索偿计数.在数据库中找到了我要登录的用户,但是在这里它的声明将返回0-在数据库中,声明确实针对该用户存在(请参见图像).

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 image).

    [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.

推荐答案

对于 UserManager.GetClaimsAsync ,它将从 AspNetUserClaims 而不是 AspNetUserRoles 查询声明代码>.您可以通过 GetClaimsAsync 进行检查>

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

通常,我们可以尝试使用 HttpContext.User.Claims 来检索用户的声明,但是它将用于子请求而不是当前的登录请求.如果将此 HttpContext.User.Claims 移至 Home Index 操作,它将返回预期结果.

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

这篇关于通过ASP .NET CORE Identity中的SignInManager登录后如何获得用户声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:37