I have a ASP.NET Core MVC application that is integrated with our Azure AD. In the default template that is created for a new MVC project, it shows the name of the logged in user, but I'd like to show the avatar as well (image associated with the user like Azure does when logging into the portal).
Can this be done?
You can use Microsoft Graph API to get the photo of the current user :
GET https://graph.microsoft.com/v1.0/me/photo/$value
Reference : https://docs.microsoft.com/en-us/graph/api/profilephoto-get?view=graph-rest-1.0
To use Microsoft Graph API , you need to get access token in your MVC application using MSAL :
private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
{
var clientCredential = new ClientCredential(context.Options.ClientSecret);
var userId = context.Principal.FindFirst(ClaimTypes.NameIdentifier).Value;
var tokenCache = new SessionTokenCache(context.HttpContext, userId);
var confidentialClientApplication = new ConfidentialClientApplication(
context.Options.ClientId,
context.Options.Authority,
_options.RedirectUri,
clientCredential,
tokenCache.GetInstance(),
null);
try
{
var authenticationResult = await confidentialClientApplication.AcquireTokenByAuthorizationCodeAsync(context.ProtocolMessage.Code, _options.ApiScopes.Split(' '));
context.HandleCodeRedemption(authenticationResult.AccessToken, authenticationResult.IdToken);
}
catch (Exception ex)
{
// TODO: Handle
throw;
}
}
please refer to code sample :
Or using the Microsoft Graph Client Library for .NET (SDK)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.