![](/img/trans.png)
[英]How to retrieve Google profile picture from logged in user with ASP.Net Core Identity?
[英]How to retrieve Facebook profile picture from logged in user with ASP.Net Core Identity?
我有一個可行的解決方案,但我想知道這是否是正確的方法。 這是我到目前為止所得到的。
我將 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.UseFacebookAuthentication(new FacebookOptions
{
AuthenticationScheme = "Facebook",
AppId = Configuration["ExternalLoginProviders:Facebook:AppId"],
AppSecret = Configuration["ExternalLoginProviders:Facebook:AppSecret"]
});
}
FacebookOptions 附帶 Microsoft.AspNetCore.Authentication.Facebook 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);
byte[] thumbnailBytes = null;
if (info.LoginProvider == "Facebook")
{
string nameIdentifier = info.Principal.FindFirstValue(ClaimTypes.NameIdentifier);
string thumbnailUrl = $"https://graph.facebook.com/{nameIdentifier}/picture?type=large";
using (HttpClient httpClient = new HttpClient())
{
thumbnailBytes = await httpClient.GetByteArrayAsync(thumbnailUrl);
}
}
//...
}
所以這段代碼工作得很好,但是,如前所述,這是正確的方法(從技術上講,不是基於意見)嗎?
要從 Facebook 獲取個人資料圖片,您需要配置 Facebook 選項並從 OAuth 訂閱 OnCreatingTicket 事件。
services.AddAuthentication().AddFacebook("Facebook", options =>
{
options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
options.ClientId = configuration.GetSection("ExternalLogin").GetSection("Facebook").GetSection("ClientId").Value;
options.ClientSecret = configuration.GetSection("ExternalLogin").GetSection("Facebook").GetSection("ClientSecret").Value;
options.Fields.Add("picture");
options.Events = new OAuthEvents
{
OnCreatingTicket = context =>
{
var identity = (ClaimsIdentity)context.Principal.Identity;
var profileImg = context.User["picture"]["data"].Value<string>("url");
identity.AddClaim(new Claim(JwtClaimTypes.Picture, profileImg));
return Task.CompletedTask;
}
};
});
在 ASP.NET Core 3.0 中,OAuthCreatingTicketContext 發生了重大變化,請參閱https://docs.microsoft.com/en-US/dotnet/core/compatibility/2.2-3.0
我變了
var profileImg = context.User["picture"]["data"].Value<string>("url");
到
var profileImg = context.User.GetProperty("picture").GetProperty("data").GetProperty("url").ToString();
我僅使用標識符從圖形 api 中獲取圖像
$"https://graph.facebook.com/{identifier}/picture?type=large";
在 asp.net core 3.1 中,我通過使用完成身份驗證時返回的訪問令牌直接調用 Facebook API 來做到這一點。 這是過程:
在控制器方法中,您可以挑戰。
var auth = await Request.HttpContext.AuthenticateAsync("Facebook");
這會將用戶重定向到瀏覽器中的 Facebook 登錄。
如果認證成功,即: auth.Succeeded && auth.Principal.Identities.Any(id => id.IsAuthenticated) && ! string.IsNullOrEmpty(auth.Properties.GetTokenValue("access_token")
auth.Succeeded && auth.Principal.Identities.Any(id => id.IsAuthenticated) && ! string.IsNullOrEmpty(auth.Properties.GetTokenValue("access_token")
檢索 facebook 提供的身份驗證令牌,如下所示: auth.Properties.GetTokenValue("access_token")
然后使用令牌手動獲取用戶的個人資料圖片,如下所示:
public async Task<string> GetFacebookProfilePicURL(string accessToken)
{
using var httpClient = new HttpClient();
var picUrl = $"https://graph.facebook.com/v5.0/me/picture?redirect=false&type=large&access_token={accessToken}";
var res = await httpClient.GetStringAsync(picUrl);
var pic = JsonConvert.DeserializeAnonymousType(res, new { data = new PictureData() });
return pic.data.Url;
}
其中,PictureData 只是一個類,表示來自 Facebook 圖形 API 的響應以及有關圖片的所有信息; 高度,寬度,網址等。
還可以使用自定義聲明操作將 json 用戶內容映射到聲明(要使用的聲明類型取決於您)。 因此圖像 url 將被添加到聲明集合中,在 OAuthEvents 中不需要(如果您不需要它們用於其他目的)。
.AddFacebook("FbCustom", x =>
{
x.AppId = settings.FacebookAppId;
x.AppSecret = settings.FacebookSecret;
x.Scope.Add("email");
x.Scope.Add("user_hometown");
x.Scope.Add("user_birthday");
x.Fields.Add("birthday");
x.Fields.Add("picture");
x.Fields.Add("name");
x.Fields.Add("email");
//HERE IS CUSTOM A MAPPING
x.ClaimActions.MapCustomJson(CustomClaimTypes.AvatarUrl,
json => json.GetProperty("picture").GetProperty("data").GetProperty("url").GetString());
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.