【问题标题】:How to get google plus profile picture in c# MVC authentication如何在 C# MVC 身份验证中获取 google plus 个人资料图片
【发布时间】:2014-04-02 18:46:16
【问题描述】:

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

我怎样才能做到这一点?

到目前为止,我使用默认的 MVC 身份验证“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


    【解决方案1】:

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

    我没有使用GoogleAuthenticationOptions,而是使用GoogleOAuth2AuthenticationOptions,这意味着您需要先在https://console.developers.google.com/project 建立一个项目才能获得ClientIdClientSecret

    1. 在该链接 (https://console.developers.google.com/project) 上,创建一个项目,然后选择它。

    2. 然后在左侧菜单中,点击“APIs & 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 保存到数据库中。

    希望对某人有所帮助。

    【讨论】:

    • gjsduarte 的答案是一个更好的答案——图片 url 作为 context.Identity.User json 数据的一部分。这个答案很接近,但它在回调中对谷歌进行了不必要的第二次调用。
    • 并且不需要在 mvc5 应用程序端声明任何路由,即 /signin-google 同时需要在 google 端为重定向 URL 输入授权重定向 URL
    【解决方案2】:

    这可能会更容易完成。不确定它是否总是这样,但这是我的代码(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 中,然后可以使用以下方法直接检索图片网址:

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

    【讨论】:

    • 这对 GoogleOAuth2 无效
    • 事件 = 新 OAuthEvents { OnCreatingTicket = 异步上下文 => { }
    • 对于 aspnet core2 我们可以使用 ClaimActions.MapJsonSubKey("profile-image-url", "image", "url")
    【解决方案3】:

    “图片” 不再有效,“url” 也不再有效。现在你只需要得到 ​​p>

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

    使用 IdentityServer4 在 .NET Core 2.2 上进行测试。 可能与最近关闭 Google+ API 有关。

    【讨论】:

    • 适合我
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-15
    • 1970-01-01
    • 2018-09-03
    • 2013-08-06
    • 2015-02-14
    • 2011-06-13
    • 1970-01-01
    相关资源
    最近更新 更多