如何在 c# MVC 身份验证中获取 google plus 个人资料图片 [英] How to get google plus profile picture in c# MVC authentication

查看:28
本文介绍了如何在 c# MVC 身份验证中获取 google plus 个人资料图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm developing a C# ASP.NET MVC 5 application that uses Google sign in as a default provider. The login functionality works ok and I can get the e-mail and name of the user. One thing that I need is to get the profile picture of the user.

我怎样才能做到这一点?

How can I achieve that?

到目前为止,我使用默认的 MVC 身份验证UseGoogleAuthentication".

So far I using the default 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);

这就是我获取电子邮件地址的方式.但是头像呢?

This is how I can get the email address. But what about the profile picture?

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

Do I need to use another form of authentication?

推荐答案

我知道这是一个迟到的答案,但在解决同样的问题时发现了你的问题.这是我的解决方案.

I know this is a late answer, but found your question while working on the same problem. Here is my solution.

我使用 GoogleOAuth2AuthenticationOptions 而不是 GoogleAuthenticationOptions,这意味着您需要在 https://console.developers.google.com/project 首先获取一个 ClientIdClientSecret.

Instead of using GoogleAuthenticationOptions I used GoogleOAuth2AuthenticationOptions which means you'll need to set up a project at https://console.developers.google.com/project first to get a ClientId and ClientSecret.

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

  1. At that link (https://console.developers.google.com/project), create a project and then select it.

然后在左侧菜单中,点击APIs & auth".

Then on the left side menu, click on "APIs & auth".

在API"下,确保您已将Google+ API"设置为开启".

Under "APIs", ensure you have "Google+ API" set to "On".

然后点击凭据"(在左侧菜单中).

Then click on "Credentials" (in the left side menu).

然后单击创建新的客户 ID"按钮.按照说明进行操作,然后您将获得 ClientIdClientSecret,请注意两者.

Then click on the button "Create new Client ID". Follow the instructions and you will then be provided with a ClientId and ClientSecret, take note of both.

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

Now you have those, the GoogleOAuth2AuthenticationOptions code looks like this:

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 中.

Notice that this also adds the access token as a claim so we can use it to retrieve the profile image. The next bit may vary depending on how you have your project set up, but for me, it was in the AccountController.

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

In my ExternalLoginCallback method I check for which login provider is being used and handle the data for Google login. In this section I retrieve the profile image url and store it in a variable with the following code:

//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 保存到数据库中.

This uses the access token to request the user info from google. It then retrieves the image url from the json data return. You can then save the url to the database in the most appropriate way for your project.

希望对某人有所帮助.

这篇关于如何在 c# MVC 身份验证中获取 google plus 个人资料图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆