我正在尝试使用.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中获取用户?
答案 0 :(得分:2)
对ExternalLoginSignInAsync
的调用未填充HttpContext.User
-最终编写了一个身份验证cookie,当尝试填充HttpContext.User
时,该请求将在后续请求中读取,但之前没有。在您的示例中,对ExternalLoginSignInAsync
的调用与对GetUserAsync
的调用在相同的请求中发生,这意味着HttpContext.User
不会代表经过身份验证的用户,因此找不到匹配项。
相反,您可以使用UserManager.FindByLoginAsync
来获取user
的正确值:
var user = await _userManager.FindByLoginAsync(
info.LoginProvider, info.ProviderKey);