gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:35:50 28 4
gpt4 key购买 nike

好的...我目前正在使用 ASP.Net Core 1.1.2 和 ASP.NET Core Identity 1.1.2。

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

    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 包。

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

所以,到目前为止一切正常。在这里我被困住了。我读了很多关于 accesstokens 和 claims called pictureUrl 等的文章。但是 Principal 不包含任何这些内容。

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

最佳答案

我在 ASP.NET Core 2.0 上遇到了同样的问题。有一种更好的方法可以从 startup.cs 中的 OnCreatingTicket 事件中检索图片。在您的情况下,您必须将特定声明“图片” 添加到身份中。

    public void ConfigureServices(IServiceCollection services)
{
services
.AddAuthentication()
.AddCookie()
.AddGoogle(options =>
{
options.ClientId = Configuration["Google.LoginProvider.ClientId"];
options.ClientSecret = Configuration["Google.LoginProvider.ClientKey"];
options.Scope.Add("profile");
options.Events.OnCreatingTicket = (context) =>
{
context.Identity.AddClaim(new Claim("image", context.User.GetValue("image").SelectToken("url").ToString()));

return Task.CompletedTask;
};
});
}

然后在您的 AccountController 中,您可以从外部登录信息方法中选择图像。

var info = await _signInManager.GetExternalLoginInfoAsync();

var picture = info.Principal.FindFirstValue("image");

关于c# - 如何使用 ASP.Net Core Identity 从登录用户检索 Google 个人资料图片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45855503/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com