【发布时间】:2020-11-24 07:47:47
【问题描述】:
我正在使用带有工作/学校帐户身份验证的 asp.net mvc。目前我正在尝试在用户进程中实现身份。
这是我的ApplicationUser 课程:
public class ApplicationUser: IdentityUser
{
public ICollection<Semester> Semesters { get; set; }
}
到目前为止,身份验证工作正常,只有一个问题。当我使用我的学校帐户登录应用程序时,我可以在控制器中将ClaimsPrincipals 称为User。要获取当前的ApplicationUser,您可以使用UserManager(await _userManager.GetUserAsync(User),User 是ClaimsPrincipals)但是由于我没有将我的学校帐户存储在数据库中,因此结果将为空。如果我创建一个新的ApplicationUser,如下所示
var newUser = new ApplicationUser()
{
UserName = User.Identity.Name,
Email = User.Identity.Name
};
await _userManager.CreateAsync(newUser);
await _userManager.AddClaimsAsync(newUser, User.Claims);
这将成功创建新用户并将其保存到带有声明的数据库中。但是当我尝试使用await _userManager.GetUserAsync(User) 获取新创建的ApplicationUser 时,结果仍然为空。如果我访问我的DbContext 并获得所有ApplicationUsers,则新创建的ApplicationUser 就在那里。那么,如何根据我从学校帐户登录获得的ClaimsPrincipals 创建ApplicationUser?
【问题讨论】:
-
您可能需要刷新声明,因为新创建的用户可能还不存在。如果在数据库中创建良好,请尝试在调用
await _userManager.AddClaimsAsync(newUser, User.Claims);后使用await _signInManager.RefreshSignInAsync(applicationUser);刷新声明 -
@Dave 这给了我以下错误:
InvalidOperationException: No authentication handler is registered for the scheme 'Identity.Application'. The registered schemes are: AzureAD, AzureADOpenID, AzureADCookie. Did you forget to call AddAuthentication().Add[SomeAuthHandler]("Identity.Application",...)?。基于此,我有了做await _userManager.AddLoginAsync(user, loginInfo)的想法。但我不知道如何检索登录信息。loginInfo必须是UserLoginInfo -
不幸的是,我不能说可能出了什么问题。可以试试this
标签: c# asp.net entity-framework