如何使用ASP.Net Core Identity从登录的用户中检索Google个人资料图片?

问题描述:

好吧...我目前正在将ASP.Net Core 1.1.2与ASP.NET Core Identity 1.1.2一起使用.

Ok... I'm currently using ASP.Net Core 1.1.2 with ASP.NET Core Identity 1.1.2.

Startup.cs 中的重要部分如下所示:

The important part in Startup.cs looks like this:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        //...
        app.UseGoogleAuthentication(new GoogleOptions
        {
            AuthenticationScheme = "Google",
            SignInScheme = "Identity.External", // this is the name of the cookie middleware registered by UseIdentity()
            ClientId = Configuration["ExternalLoginProviders:Google:ClientId"],
            ClientSecret = Configuration["ExternalLoginProviders:Google:ClientSecret"]
        });
    }

GoogleOptions随附Microsoft.AspNetCore.Authentication.Google nuget软件包.

GoogleOptions comes with Microsoft.AspNetCore.Authentication.Google nuget package.

AccountController.cs 中的回调函数如下:

    [HttpGet]
    [AllowAnonymous]
    public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
    {
        //... SignInManager<User> _signInManager; declared before
        ExternalLoginInfo info = await _signInManager.GetExternalLoginInfoAsync();
        SignInResult signInResult = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);
        string email = info.Principal.FindFirstValue(ClaimTypes.Email);
        string firstName = info.Principal.FindFirstValue(ClaimTypes.GivenName);
        string lastName = info.Principal.FindFirstValue(ClaimTypes.Surname);
        //
    }

因此,到目前为止一切正常.在这里我被卡住了.我阅读了很多有关访问令牌和声明的文章,它们称为pictureUrl等.但是Principal不包含任何这些.

So, everything works fine until this point. And here I'm stuck. I read a lot of articles about accesstokens and claims called pictureUrl and so on. But the Principal doesn't contain any of those.

问题是:如何在ExternalLoginCallback函数中一次检索个人资料图像?

So the question is: How to retrieve the profile image once in the ExternalLoginCallback function?

我找不到从声明中获取图片网址的方法.最终,我找到了使用声明附带的nameidentifier的解决方案.

I found no way to get the picture url from the claims. Finally I found a solution using the nameidentifier, which comes with the claims.

string googleApiKey = _configurationRoot["ExternalLoginProviders:Google:ApiKey"];
ExternalLoginInfo info = await _signInManager.GetExternalLoginInfoAsync();
string nameIdentifier = info.Principal.FindFirstValue(ClaimTypes.NameIdentifier);
string jsonUrl = $"https://www.googleapis.com/plus/v1/people/{nameIdentifier}?fields=image&key={googleApiKey}";
using (HttpClient httpClient = new HttpClient())
{
    string s = await httpClient.GetStringAsync(jsonUrl);
    dynamic deserializeObject = JsonConvert.DeserializeObject(s);
    string thumbnailUrl = (string)deserializeObject.image.url;
    byte[] thumbnail = await httpClient.GetByteArrayAsync(thumbnailUrl);
}

您需要的只是一个Google API密钥.

All you need is a Google API key.

要创建API密钥,请执行以下操作:

To create an API key:

  1. 转到Google API控制台.
  2. 从项目下拉列表中,选择一个项目,或创建一个新项目.
  3. 启用Google+ API服务:

  1. Go to the Google API Console.
  2. From the project drop-down, select a project , or create a new one.
  3. Enable the Google+ API service:

a.在Google API列表中,搜索Google+ API服务.

a. In the list of Google APIs, search for the Google+ API service.

b.从结果列表中选择Google+ API.

b. Select Google+ API from the results list.

c.按启用API"按钮.

c. Press the Enable API button.

该过程完成后,Google + API会显示在已启用的API列表中.到 访问,请选择API&左侧工具栏菜单上的服务,然后选择 启用的API标签.

When the process completes, Google+ API appears in the list of enabled APIs. To access, select APIs & Services on the left sidebar menu, then select the Enabled APIs tab.

在"API和服务"下的侧栏中,选择凭据".

In the sidebar under "APIs & Services", select Credentials.

https://developers.google.com/+/web/api/rest/oauth