Microsoft.Identity.Web 會抽象化 MSAL.NET 的複雜性。 它提供您處理 MSAL.NET 內部的較高層級 API,例如處理條件式存取錯誤、快取。
以下是呼叫下游 API 的精靈應用程式Program.cs:
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Identity.Abstractions;
using Microsoft.Identity.Web;
// In the Program.cs, acquire a token for your downstream API
var tokenAcquirerFactory = TokenAcquirerFactory.GetDefaultInstance();
tokenAcquirerFactory.Services.AddDownstreamApi("MyApi",
tokenAcquirerFactory.Configuration.GetSection("MyWebApi"));
var sp = tokenAcquirerFactory.Build();
var api = sp.GetRequiredService<IDownstreamApi>();
var result = await api.GetForAppAsync<IEnumerable<TodoItem>>("MyApi");
Console.WriteLine($"result = {result?.Count()}");
以下是呼叫 Microsoft Graph 的精靈應用程式的Program.cs:
var tokenAcquirerFactory = TokenAcquirerFactory.GetDefaultInstance();
tokenAcquirerFactory.Services.AddMicrosoftGraph();
var serviceProvider = tokenAcquirerFactory.Build();
try
{
GraphServiceClient graphServiceClient = serviceProvider.GetRequiredService<GraphServiceClient>();
var users = await graphServiceClient.Users
.GetAsync(r => r.Options.WithAppOnly());
Console.WriteLine($"{users.Count} users");
Console.ReadKey();
}
catch (Exception ex) { Console.WriteLine("We could not retrieve the user's list: " + $"{ex}"); }
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Set the appropriate header fields in the request header.
conn.setRequestProperty("Authorization", "Bearer " + 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);
使用 Axios 之類的 HTTP 用戶端,以存取令牌作為授權持有人呼叫 API 端點 URI。
const axios = require('axios');
async function callApi(endpoint, accessToken) {
const options = {
headers: {
Authorization: `Bearer ${accessToken}`
}
};
console.log('request made to web API at: ' + new Date().toString());
try {
const response = await axios.default.get(endpoint, options);
return response.data;
} catch (error) {
console.log(error)
return error;
}
};
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()
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);
...
}
針對精靈應用程式,您必須預先核准您呼叫的 Web API。 精靈應用程式沒有累加式同意。 (沒有用戶互動。租用戶系統管理員必須事先為應用程式和所有 API 許可權提供同意。 如果您想要呼叫數個 API,請在每次呼叫 AcquireTokenForClient
時取得每個資源的令牌。 MSAL 會使用應用程式令牌快取來避免不必要的服務呼叫。