![](/img/trans.png)
[英]How to retrieve Facebook profile picture from logged in user with ASP.Net Core Identity?
[英]How can I get Google and Facebook profile picture from logged in user in a controller with ASP.Net Core Identity 3.1?
如何使用ASP.Net Core Identity 3.1
從 controller 中的登錄用戶獲取 Google 和 Facebook 個人資料圖片?
services.AddAuthentication().AddGoogle(opts =>
{
opts.ClaimActions.MapJsonKey("urn:google:picture", "picture", "url");
opts.ClaimActions.MapJsonKey("urn:google:locale", "locale", "string");
opts.SaveTokens = true;
opts.Events.OnCreatingTicket = ctx =>
{
List<AuthenticationToken> tokens = ctx.Properties.GetTokens().ToList();
tokens.Add(new AuthenticationToken()
{
Name = "TicketCreated",
Value = DateTime.UtcNow.ToString()
});
ctx.Properties.StoreTokens(tokens);
return Task.CompletedTask;
};
}
回調方法:
public async Task<IActionResult> GoogleResponse(string returnUrl = "/")
{
ExternalLoginInfo info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return RedirectToAction(nameof(Login));
}
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider,
info.ProviderKey,
false);
if (result.Succeeded)
{
var picture = info.Principal.FindFirstValue("urn:google:picture");
// Should I save picture in User table? (User table has this 'public string PhotoFileName { get; set; }' property)
var locale = info.Principal.FindFirstValue("urn:google:locale");
return Redirect(returnUrl);
}
else
{
User user = new User
{
Email = info.Principal.FindFirst(ClaimTypes.Email).Value,
UserName = info.Principal.FindFirst(ClaimTypes.Email).Value,
EmailConfirmed = true,
IpAddress = GetClientIpAddress(),
FirstName = info.Principal.FindFirstValue(ClaimTypes.GivenName),
LastName = info.Principal.FindFirstValue(ClaimTypes.Surname)
};
IdentityResult identResult = await _userManager.CreateAsync(user);
if (identResult.Succeeded)
{
await _userManager.AddToRoleAsync(user, PolicyTypes.OrdinaryUsers);
identResult = await _userManager.AddLoginAsync(user, info);
if (identResult.Succeeded)
{
// If they exist, add claims to the user for:
// Given (first) name
// Locale
// Picture
if (info.Principal.HasClaim(c => c.Type == ClaimTypes.GivenName))
{
await _userManager.AddClaimAsync(user,
info.Principal.FindFirst(ClaimTypes.GivenName));
}
if (info.Principal.HasClaim(c => c.Type == "urn:google:locale"))
{
await _userManager.AddClaimAsync(user,
info.Principal.FindFirst("urn:google:locale"));
}
if (info.Principal.HasClaim(c => c.Type == "urn:google:picture"))
{
await _userManager.AddClaimAsync(user,
info.Principal.FindFirst("urn:google:picture"));
}
// Include the access token in the properties
var props = new AuthenticationProperties();
props.StoreTokens(info.AuthenticationTokens);
props.IsPersistent = true;
await _signInManager.SignInAsync(user, props);
return LocalRedirect(returnUrl);
}
}
return AccessDenied();
}
}
評論控制器:
public class CommentController : BaseController
{
private readonly ICommentRepository _commentRepository;
private UserManager<User> _userManager;
public CommentController(ICommentRepository commentRepository, UserManager<User> userManager)
{
_commentRepository = commentRepository;
_userManager = userManager;
}
}
看來您已將語言環境和圖片信息保存到AspNetUserClaims
表中。 如果用戶通過了認證,在 controller 中,您可以通過以下方式直接查詢信息:
var user =await _userManager.GetUserAsync(User);
var claims = await _userManager.GetClaimsAsync(user);
var locale = claims.Where(x => x.Type == "urn:google:locale").FirstOrDefault().Value;
var picture = claims.Where(x => x.Type == "urn:google:picture").FirstOrDefault().Value;
我已將“urn:google:picture”替換為“picture”以進行概括,然后:
ExternalLoginCallback 方法:
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = "/")
{
ExternalLoginInfo info = await _signInManager.GetExternalLoginInfoAsync();
if (info.LoginProvider == "Google")
{
await _userManager.AddClaimAsync(user, info.Principal.FindFirst("picture"));
}
else if (info.LoginProvider == "Facebook")
{
var identifier = info.Principal.FindFirstValue(ClaimTypes.NameIdentifier);
var thumbnailUrl = $"https://graph.facebook.com/{identifier}/picturetype=album";
await _userManager.AddClaimAsync(user, new Claim("picture",thumbnailUrl));
}
}
在 Controller 中:
var claims = await _userManager.GetClaimsAsync(new User { Id = userId });
var claim = claims.FirstOrDefault(x => x.Type == "picture");
var picture = claim.Value;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.