如何在c#MVC身份验证中获取google plus个人资料图片

问题描述 投票:12回答:3

我正在开发一个使用Google登录作为默认提供程序的C#ASP.NET MVC 5应用程序。登录功能正常,我可以获得用户的电子邮件和名称。我需要的一件事是获取用户的个人资料图片。

我怎样才能做到这一点?

到目前为止,我使用默认的MVC auth“UseGoogleAuthentication”。

Microsoft.Owin.Security.Google.GoogleAuthenticationOptions a = new Microsoft.Owin.Security.Google.GoogleAuthenticationOptions();

var googleOption = new GoogleAuthenticationOptions()
{
    Provider = new GoogleAuthenticationProvider()
    {
         OnAuthenticated = (context) =>
         {
              var rawUserObjectFromFacebookAsJson = context.Identity;
              context.Identity.AddClaim(new Claim("urn:google:name", context.Identity.FindFirstValue(ClaimTypes.Name)));
              context.Identity.AddClaim(new Claim("urn:google:email", context.Identity.FindFirstValue(ClaimTypes.Email)));
              return Task.FromResult(0);
         }
    }
};

app.UseGoogleAuthentication(googleOption);

这就是我如何获得电子邮件地址。但是个人资料图片怎么样?

我是否需要使用其他形式的身份验证?

c# asp.net-mvc gmail google-plus
3个回答
28
投票

我知道这是一个迟到的答案,但在处理同样的问题时找到了你的问题。这是我的解决方案。

而不是使用GoogleAuthenticationOptions我使用GoogleOAuth2AuthenticationOptions这意味着你需要首先在https://console.developers.google.com/project建立一个项目来获得ClientIdClientSecret

  1. 在该链接(https://console.developers.google.com/project),创建一个项目,然后选择它。
  2. 然后在左侧菜单中,单击“API&auth”。
  3. 在“API”下,确保将“Google+ API”设置为“开启”。
  4. 然后单击“凭据”(在左侧菜单中)。
  5. 然后单击“创建新客户端ID”按钮。按照说明,然后您将获得ClientIdClientSecret,注意两者。

现在你有了这些,GoogleOAuth2AuthenticationOptions代码如下所示:

var googleOptions = new GoogleOAuth2AuthenticationOptions()
{
    ClientId = [INSERT CLIENT ID HERE],
    ClientSecret = [INSERT CLIENT SECRET HERE],
    Provider = new GoogleOAuth2AuthenticationProvider()
    {
        OnAuthenticated = (context) =>
        {
            context.Identity.AddClaim(new Claim("urn:google:name", context.Identity.FindFirstValue(ClaimTypes.Name)));
            context.Identity.AddClaim(new Claim("urn:google:email", context.Identity.FindFirstValue(ClaimTypes.Email)));
            //This following line is need to retrieve the profile image
            context.Identity.AddClaim(new System.Security.Claims.Claim("urn:google:accesstoken", context.AccessToken, ClaimValueTypes.String, "Google"));

            return Task.FromResult(0);
        }
    }
};

app.UseGoogleAuthentication(googleOptions);

请注意,这也会将访问令牌添加为声明,因此我们可以使用它来检索配置文件图像。下一位可能会有所不同,具体取决于您的项目设置方式,但对我来说,它是在AccountController

在我的ExternalLoginCallback方法中,我检查正在使用哪个登录提供程序并处理Google登录的数据。在本节中,我将检索配置文件图像URL并使用以下代码将其存储在变量中:

//get access token to use in profile image request
var accessToken = loginInfo.ExternalIdentity.Claims.Where(c => c.Type.Equals("urn:google:accesstoken")).Select(c => c.Value).FirstOrDefault();
Uri apiRequestUri = new Uri("https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + accessToken);
//request profile image
using (var webClient = new System.Net.WebClient())
{
    var json = webClient.DownloadString(apiRequestUri);
    dynamic result = JsonConvert.DeserializeObject(json);
    userPicture = result.picture;
}

这使用访问令牌从谷歌请求用户信息。然后它从json数据返回中检索图像url。然后,您可以以最合适的方式将URL保存到数据库中。

希望能帮助别人。


6
投票

这可能会更容易。不确定它是否总是这样,但这是我的代码(ASP.NET 5):

private static Task OnGoogleAuthenticated(GoogleAuthenticatedContext context)
{
    var identity = ((ClaimsIdentity)context.Principal.Identity);
    var pictureUrl = context.User["image"].Value<string>("url");
    // Pass the picture url as a claim to be used later in the application
    identity.AddClaim(new Claim("pictureUrl", pictureUrl));
    return Task.FromResult(0);
}

在ExternalLoginCallback中,然后可以使用以下命令直接检索pictureUrl:

var info = await signInManager.GetExternalLoginInfoAsync();
...
var picture = info.ExternalPrincipal.FindFirstValue("pictureUrl");

0
投票

“图像”不再有效,也不再是“网址”。现在你只需要得到

context.User["picture"].ToString()

使用IdentityServer4在.NET Core 2.2上进行了测试。也许这与Google+ API的最新关闭有关。

© www.soinside.com 2019 - 2024. All rights reserved.