我正在开发一个小型 MVC5 网站,该网站使用 Google 身份验证,但我想在没有 ASP.NET Identity 的情况下完成此操作。
到目前为止,我已按照此博文中的步骤操作并拥有有效的登录名:http://coding.abel.nu/2014/11/using-owin-external-login-without-asp-net-identity/
但是当前 User.Identity.Name 被设置为用户的全名。我想将其设置为用户的电子邮件地址,因为我更喜欢将其设置为用户的主键。到目前为止,我的代码仅包含该博客文章中的内容。
我可以使用以下代码检索用户的电子邮件地址,但这只是在用户通过身份验证之后。
ClaimsPrincipal.Current.FindFirst(ClaimTypes.Email).Value;
我尝试覆盖 GoogleOAuth2ProviderOptions 的 OnAuthenticated,发现有一个 NameClaimType 但它是只读的。
app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions
{
ClientId = "...",
ClientSecret = "...",
Provider = new GoogleOAuth2AuthenticationProvider()
{
OnAuthenticated = async context =>
{
context.Identity.NameClaimType = ClaimTypes.Email;
}
}
});
我还没有找到任何其他东西可以让我设置 User.Identity.Name 的设置。有什么想法吗?
最佳答案
在一般用法中,当用户注册 Google 帐户时,会创建一个新的本地帐户并将其链接到 Google 登录信息。您需要如下创建该用户。 (摘自模板)
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user);
这里,您需要将用户名字段设置为您需要的电子邮件
关于asp.net - 通过 Google OAuth2 登录时设置 User.Identity.Name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29304020/