MSAL.NET 中的 AuthenticationResult 屬性
取得權杖的方法會傳回 AuthenticationResult
。 針對異步方法, Task<AuthenticationResult>
會傳回 。
在 MSAL.NET 中, AuthenticationResult
公開:
AccessToken
供 Web API 存取資源。 此參數是字串,通常是Base-64編碼的JWT。 用戶端絕對不應該在存取令牌內查看。 格式不保證會保持穩定,而且可以加密資源。 撰寫依賴用戶端存取令牌內容的程式代碼,是錯誤和客戶端邏輯中斷的最大來源之一。 如需詳細資訊,請參閱 存取令牌。
IdToken
使用者。 此參數是編碼的 JWT。 如需詳細資訊,請參閱 標識符令牌。
ExpiresOn
告知令牌到期的日期和時間。
TenantId
包含找到使用者的租使用者。 針對 Microsoft Entra B2B 案例中的來賓使用者,租使用者標識碼是來賓租使用者,而不是唯一租使用者。
為用戶傳遞令牌時, AuthenticationResult
也包含此用戶的相關信息。 對於要求令牌且沒有應用程式使用者的機密用戶端流程,此使用者資訊為 null。
Scopes
發出權杖的 。
- 使用者的唯一識別碼。
IAccount
MSAL.NET 透過 IAccount
介面定義帳戶的概念。 這項重大變更提供正確的語意。 相同的用戶可以在不同的 Microsoft Entra 目錄中擁有數個帳戶。 此外,MSAL.NET 客體案例中提供更佳的信息,因為提供主帳戶資訊。
下圖顯示 介面的結構 IAccount
。
類別 AccountId
會識別特定租使用者中的帳戶,其中包含下表所示的屬性。
屬性 |
說明 |
TenantId |
GUID 的字串表示,這是帳戶所在租用戶的標識碼。 |
ObjectId |
GUID 的字串表示,這是在租用戶中擁有帳戶的使用者標識碼。 |
Identifier |
帳戶的唯一標識碼。 Identifier 是的 ObjectId 串連,並以 TenantId 逗號分隔。 它們不是Base 64編碼。 |
介面 IAccount
代表單一帳戶的相關信息。 相同的使用者可以存在於不同的租使用者中,這表示使用者可以有多個帳戶。 下表顯示其成員。
屬性 |
說明 |
Username |
字串,包含 UserPrincipalName (UPN) 格式的可顯示值,例如 john.doe@contoso.com。 此字串可以是 null,不同於 HomeAccountId 和 HomeAccountId.Identifier,這不會是 Null。 這個屬性會 DisplayableId 取代舊版 MSAL.NET 中的屬性 IUser 。 |
Environment |
字串,包含此帳戶的識別提供者,例如 login.microsoftonline.com 。 這個屬性會 IdentityProvider 取代的 IUser 屬性,但 IdentityProvider 除了雲端環境之外,也包含租用戶的相關信息。 在這裡,值只是主機。 |
HomeAccountId |
使用者主帳戶的帳戶標識碼。 此屬性可唯一識別 Microsoft Entra 租用戶的使用者。 |
使用令牌來呼叫受保護的 API
在 中result
由 MSAL 傳回 之後AuthenticationResult
,請先將它新增至 HTTP 授權標頭,再進行呼叫以存取受保護的 Web API。
httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
// Call the web API.
HttpResponseMessage response = await _httpClient.GetAsync(apiUri);
...
}
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
PublicClientApplication pca = PublicClientApplication.builder(clientId)
.authority(authority)
.build();
// Acquire a token, acquireTokenHelper would call publicClientApplication's acquireTokenSilently then acquireToken
// see https://github.com/Azure-Samples/ms-identity-java-desktop for a full example
IAuthenticationResult authenticationResult = acquireTokenHelper(pca);
// Set the appropriate header fields in the request header.
conn.setRequestProperty("Authorization", "Bearer " + authenticationResult.accessToken);
conn.setRequestProperty("Accept", "application/json");
String response = HttpClientHelper.getResponseStringFromConn(conn);
int responseCode = conn.getResponseCode();
if(responseCode != HttpURLConnection.HTTP_OK) {
throw new IOException(response);
}
JSONObject responseObject = HttpClientHelper.processResponse(responseCode, response);
在 MSAL for iOS 和 macOS 中呼叫 Web API
取得令牌的方法會傳回 MSALResult
物件。 MSALResult
會 accessToken
公開可用來呼叫 Web API 的屬性。 在呼叫存取受保護的 Web API 之前,請先將存取令牌新增至 HTTP 授權標頭。
Objective-C:
NSMutableURLRequest *urlRequest = [NSMutableURLRequest new];
urlRequest.URL = [NSURL URLWithString:"https://contoso.api.com"];
urlRequest.HTTPMethod = @"GET";
urlRequest.allHTTPHeaderFields = @{ @"Authorization" : [NSString stringWithFormat:@"Bearer %@", accessToken] };
NSURLSessionDataTask *task =
[[NSURLSession sharedSession] dataTaskWithRequest:urlRequest
completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {}];
[task resume];
Swift:
let urlRequest = NSMutableURLRequest()
urlRequest.url = URL(string: "https://contoso.api.com")!
urlRequest.httpMethod = "GET"
urlRequest.allHTTPHeaderFields = [ "Authorization" : "Bearer \(accessToken)" ]
let task = URLSession.shared.dataTask(with: urlRequest as URLRequest) { (data: Data?, response: URLResponse?, error: Error?) in }
task.resume()
呼叫數個 API:累加式同意和條件式存取
若要為相同的使用者呼叫數個 API,請在取得第一個 API 的權杖之後,呼叫 AcquireTokenSilent
。 您大部分時間都會以無訊息方式取得其他 API 的令牌。
var result = await app.AcquireTokenXX("scopeApi1")
.ExecuteAsync();
result = await app.AcquireTokenSilent("scopeApi2")
.ExecuteAsync();
在下列情況下需要互動:
- 使用者已同意第一個 API,但現在需要同意更多範圍。 這種同意稱為累加式同意。
- 第一個 API 不需要多重要素驗證,但下一個 API 會執行。
var result = await app.AcquireTokenXX("scopeApi1")
.ExecuteAsync();
try
{
result = await app.AcquireTokenSilent("scopeApi2")
.ExecuteAsync();
}
catch(MsalUiRequiredException ex)
{
result = await app.AcquireTokenInteractive("scopeApi2")
.WithClaims(ex.Claims)
.ExecuteAsync();
}
使用 Axios 之類的 HTTP 用戶端,以存取令牌作為授權持有人呼叫 API 端點 URI。
const axios = require('axios');
async function callEndpointWithToken(endpoint, accessToken) {
const options = {
headers: {
Authorization: `Bearer ${accessToken}`
}
};
console.log('Request made at: ' + new Date().toString());
const response = await axios.default.get(endpoint, options);
return response.data;
}
endpoint = "url to the API"
http_headers = {'Authorization': 'Bearer ' + result['access_token'],
'Accept': 'application/json',
'Content-Type': 'application/json'}
data = requests.get(endpoint, headers=http_headers, stream=False).json()