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

Setting User.Identity.Name when logging via Google OAuth2

我正在开发一个使用 Google 身份验证的小型 MVC5 网站,但我想在没有 ASP.NET 身份的情况下进行。

到目前为止,我已按照此博客中的步骤进行操作 post 并且可以正常登录:http://coding.abel.nu/2014/11/using-owin-external-login-without-asp-net-identity/

但是目前 User.Identity.Name 被设置为用户的全名。我想将它设置为用户的电子邮件地址,因为我更喜欢将它设置为我的用户的主键。到目前为止,我的代码仅包含该博客 post.

中的内容

我可以使用以下代码检索用户的电子邮件地址,但这只能在用户通过身份验证后才能进行。

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);

这里需要根据需要将用户名字段设置为email

我想我修好了。我创建了自己的 IGoogleOAuth2AuthenticationProvider 实现,它删除了名称声明并使用 Google 提供的电子邮件重新添加它。不确定这是否是最好的方法,但它有效。

public class GoogleAuthProvider : IGoogleOAuth2AuthenticationProvider 
{
    public void ApplyRedirect(GoogleOAuth2ApplyRedirectContext context)
    {
        context.Response.Redirect(context.RedirectUri);
    }

    public System.Threading.Tasks.Task Authenticated(GoogleOAuth2AuthenticatedContext context)
    {
        context.Identity.RemoveClaim(context.Identity.FindFirst(ClaimTypes.Name));
        context.Identity.AddClaim(new Claim(ClaimTypes.Name, context.Email));
        context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email));
        return Task.FromResult<object>(null);
    }

    public System.Threading.Tasks.Task ReturnEndpoint(GoogleOAuth2ReturnEndpointContext context)
    {
        return Task.FromResult<object>(null);
    }
}

然后在设置 GoogleOauth

时连接提供者
app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions
            {
                ClientId = "...",
                ClientSecret = "...",
                Provider = new GoogleAuthProvider()
            });