无法找到用户id
本文关键字:用户 id | 更新日期: 2023-09-27 18:11:43
我真的刚刚开始接触这个LinkedIn API和ASP。NET MVC,所以请耐心听我说。我试图验证我的用户,这似乎是工作,但当我试图存储accessToken值(这似乎也是有效的),我得到错误:
"Exception Details: System. "InvalidOperationException: UserId未找到。"
错误发生在注释"//error occurs HERE"
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
return RedirectToAction("Login");
}
var claimsIdentity = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);
if (claimsIdentity != null)
{
var userIdClaim = claimsIdentity.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier);
if (userIdClaim != null)
{
// userIdClaim.Value here is: 5-0Vfh4Gv_
var accessToken = claimsIdentity.FindAll(loginInfo.Login.LoginProvider + "_AccessToken").First();
if (accessToken != null)
{
// gets to this point, but...
await UserManager.AddClaimAsync(userIdClaim.Value, accessToken); // ERROR OCCURS HERE
}
}
}
... ... ...
}
此代码99%来自Visual Studio中的MVC应用程序模板。我唯一改变的是添加领英NuGet包(安装包领英),并在Startup.Auth.cs中设置我的API密钥/秘密。完全有可能(甚至很可能)我只是做了一些没有顺序的事情,或者错误地获取了用户ID。
我已经看了我能找到的每一个例子和视频,但仍然不明白。
有谁能帮我解决这个用户错误信息,还有,我只是错过了一些一般的最佳实践的东西吗?感到失落和沮丧……
谢谢!
错误信息说明了一切。我认为你没有正确获取用户Id。
试
await UserManager.AddClaimAsync(claimsIdentity.GetUserId(), accessToken);
不是
await UserManager.AddClaimAsync(userIdClaim.Value, accessToken);
问题是在这一点上:
await UserManager.AddClaimAsync(userIdClaim.Value, accessToken);
第一个参数应该是用户在身份数据库表中的UserId
(即aspnetusers
)。
您正在从LinkedIn传入nameidentifer
-因此,该用户在您的数据库中不存在。
我认为您需要首先检查外部用户是否已经注册,如果没有,然后创建帐户,添加外部登录,然后添加索赔