簡體   English   中英

使用Azure AD身份驗證(B2C)顯示Core MVC的頭像

[英]Showing avatar for Core MVC using Azure AD Authentication (B2C)

我有一個與我們的Azure AD集成的ASP.NET Core MVC應用程序。 在為新的MVC項目創建的默認模板中,它顯示了登錄用戶的名稱,但是我也想顯示化身(與用戶關聯的圖像就像Azure在登錄門戶時一樣)。

能做到嗎?

您可以使用Microsoft Graph API獲取當前用戶的照片:

GET https://graph.microsoft.com/v1.0/me/photo/$value

參考: https : //docs.microsoft.com/zh-cn/graph/api/profilephoto-get?view=graph-rest-1.0

要使用Microsoft Graph API,您需要使用MSAL在MVC應用程序中獲取訪問令牌:

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

請參考代碼示例:

https://github.com/chrispadgettlivecom/WebApp-OpenIDConnect-DotNetCore21/tree/master/WebApp-OpenIDConnect-DotNetCore21

或使用Microsoft Graph Client Library for .NET(SDK)

https://github.com/microsoftgraph/aspnetcore-connect-sample

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM