asp.net - 通过 Google OAuth2 登录时设置 User.Identity.Name

标签 asp.net oauth-2.0 asp.net-mvc-5 google-oauth

我正在开发一个小型 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/

相关文章:

javascript - 从 ASP.NET 中的操作方法检索 Json 对象

c# - 如何将 ApplicationDbContext 传递给 ASP.NET MVC5 构造函数?

java - 无法使用 Google API [google-oauth-java-client-1.12.0-beta] 为服务帐户流获取 token

asp.net-mvc - ASP.NET MVC5/IIS Express 无法调试 - 代码未运行

ajax - MVC 5无效的JSON原语

c# - 如何传递正确的 Model Diction 类型 MVC

jquery - 使用 NuGet 更新 jquery 和现代化时自动更新脚本引用

c# - Log4Net 与应用程序洞察

security - JWT 和 OAuth2 - 服务器是否存储 token ?以及它们如何安全/黑客安全?

Azure AD B2C - GitHub 的自定义提供程序无法获取访问 token