登录后从Usermanger获取用户

时间:2018-12-16 16:26:38

标签: c# asp.net-core asp.net-core-identity

我正在尝试使用.Net-Core和IdentityServer4从外部登录后的usermanger中获取用户

public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
{
    if (remoteError != null)
    {
        ErrorMessage = $"Error from external provider: {remoteError}";
        return RedirectToAction(nameof(Login));
    }
    var info = await _signInManager.GetExternalLoginInfoAsync();
    if (info == null)
    {
        return RedirectToAction(nameof(Login));
    }

    // Sign in the user with this external login provider if the user already has a login.
    var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true);
    if (result.Succeeded)
    {
        var user = await _userManager.GetUserAsync(HttpContext.User);
        var serviceProvider = HttpContext.RequestServices;
        var context = serviceProvider.GetRequiredService<PublicAstootContext>();
        var coinbaseRule = new CoinbaseRule();
        await coinbaseRule.UpdateCoinbaseAccountInfo(context, user.Id, info);    
        //...
    }
}

但是,即使登录成功后,当我尝试从usermanger中获取用户时,该用户始终为null。

如何在外部登录后从usermanger中获取用户?

1 个答案:

答案 0 :(得分:2)

ExternalLoginSignInAsync的调用未填充HttpContext.User-最终编写了一个身份验证cookie,当尝试填充HttpContext.User时,该请求将在后续请求中读取,但之前没有。在您的示例中,对ExternalLoginSignInAsync的调用与对GetUserAsync的调用在相同的请求中发生,这意味着HttpContext.User不会代表经过身份验证的用户,因此找不到匹配项。

相反,您可以使用UserManager.FindByLoginAsync来获取user的正确值:

var user = await _userManager.FindByLoginAsync(
    info.LoginProvider, info.ProviderKey);