簡體   English   中英

在與Azure AD B2C集成的網站中獲取訪問令牌

[英]Get access token in web site integrated with Azure AD B2C

我有一個ASP.NET MVC Core 2.2應用程序,它與Azure AD B2C集成以驗證用戶身份。 我可以正確登錄,並且用戶已通過身份驗證。

我還創建了一個ASP.NET Core Web API,它也與Azure B2C AD集成,目標是從ASP.NET MVC控制器操作方法調用該Web api。

所以我在MVC站點的控制器中添加了以下測試代碼:

if (HttpContext.User.Identity.IsAuthenticated)
{
    string signedInUserID = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
    TokenCache userTokenCache = new MSALSessionCache(signedInUserID, HttpContext).GetMsalCacheInstance();
    ConfidentialClientApplication cca = new ConfidentialClientApplication(mgpPortalApplicationId, authority, redirectUri, new ClientCredential(mgpPortalSecretKey), userTokenCache, null);                
    IEnumerable<IAccount> accounts = await cca.GetAccountsAsync();
    IAccount firstAccount = accounts.FirstOrDefault();
    AuthenticationResult result = await cca.AcquireTokenSilentAsync(null, firstAccount, authority, false);
    HttpClient client = new HttpClient();
    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "https://localhost:44307/api/values");
    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
    HttpResponseMessage response = await client.SendAsync(request);
}

問題是accounts.FirstOrDefault()返回null。 不確定原因:

有沒有人知道我做錯了什么? 謝謝你的任何提示!

附加觀察:如果我運行演示https://github.com/Azure-Samples/active-directory-b2c-dotnetcore-webapp ,它使用較舊的Microsoft.Identity.Client,則調用cca.Users.FirstOrDefault( )正確回饋用戶。 但是,當我將此演示項目升級到Microsoft.Identity.Client 2.7(.NET Core 2.2需要)時,我必須傳遞一個IAccount,因此我需要調用GetAccountsAsync() ,這不會返回任何帳戶。

首先,在調用AcquireTokenSilentAsync時,您需要詢問訪問api所需的范圍

AuthenticationResult result = await cca.AcquireTokenSilentAsync(scope, cca.Users.FirstOrDefault(), AzureAdB2COptions.Authority, false);

您需要使用授權中間件的AuthorizationCodeReceived通知實現初始令牌獲取並在MSAL令牌緩存中保存令牌:

public async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
{
    // Use MSAL to swap the code for an access token
    // Extract the code from the response notification
    var code = context.ProtocolMessage.Code;

    string signedInUserID = context.Principal.FindFirst(ClaimTypes.NameIdentifier).Value;
    TokenCache userTokenCache = new MSALSessionCache(signedInUserID, context.HttpContext).GetMsalCacheInstance();
    ConfidentialClientApplication cca = new ConfidentialClientApplication(AzureAdB2COptions.ClientId, AzureAdB2COptions.Authority, AzureAdB2COptions.RedirectUri, new ClientCredential(AzureAdB2COptions.ClientSecret), userTokenCache, null);
    try
    {
        AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, AzureAdB2COptions.ApiScopes.Split(' '));


        context.HandleCodeRedemption(result.AccessToken, result.IdToken);
    }
    catch (Exception ex)
    {
        //TODO: Handle
        throw;
    }
}

因此,當在控制器中獲取令牌時,MSAL將查找緩存並返回符合要求的任何緩存令牌。 如果此類訪問令牌已過期或者沒有合適的訪問令牌,但存在關聯的刷新令牌,則MSAL將自動使用該令牌獲取新的訪問令牌並以透明方式返回:

// Retrieve the token with the specified scopes
var scope = AzureAdB2COptions.ApiScopes.Split(' ');
string signedInUserID = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
TokenCache userTokenCache = new MSALSessionCache(signedInUserID, this.HttpContext).GetMsalCacheInstance();
ConfidentialClientApplication cca = new ConfidentialClientApplication(AzureAdB2COptions.ClientId, AzureAdB2COptions.Authority, AzureAdB2COptions.RedirectUri, new ClientCredential(AzureAdB2COptions.ClientSecret), userTokenCache, null);

AuthenticationResult result = await cca.AcquireTokenSilentAsync(scope, cca.Users.FirstOrDefault(), AzureAdB2COptions.Authority, false);

下面是使用ASP.NET Core 2.0和MSAL 2的代碼示例,請閱讀README.md以獲取詳細說明。

您還可以單擊此處以獲取針對Azure AD B2C對用戶進行身份驗證的代碼示例,並使用ASP.NET Core 2.1使用MSAL.NET獲取訪問令牌。

.NETCore B2C Web應用程序已更新為使用MSAL v2.7。 使用的范圍不正確,因此示例現在使用正確的范圍並返回訪問令牌。

"ApiScopes": "https://fabrikamb2c.onmicrosoft.com/helloapi/demo.read"

@ L-Four,實際上你提到的代碼的一個分支已經更新到最新版本的MSAL: active-directory-b2c-dotnetcore-webapp

說,在運行它時,我收到了未經授權的錯誤。 所以不確定那是怎么回事。 但我確實得到了一個帳戶。

暫無
暫無

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

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