受保護的 Web API:程式代碼設定
若要設定受保護 Web API 的程式碼,請瞭解:
- 將 API 定義為受保護的專案。
- 如何設定持有人令牌。
- 如何驗證令牌。
哪些專案會將 ASP.NET 和 ASP.NET 核心 API 定義為受保護?
如同 Web 應用程式,ASP.NET 和 ASP.NET Core Web API 會受到保護,因為它們的控制器動作前面會加上 [Authorize] 屬性。 只有在使用授權的身分識別呼叫 API 時,才能呼叫控制器動作。
請考量下列問題:
- 只有應用程式可以呼叫 Web API。 API 如何知道呼叫應用程式的身分識別?
- 如果應用程式代表使用者呼叫 API,該使用者的身分識別為何?
持有人令牌
呼叫應用程式時,在標頭中設定的持有人令牌會保存應用程式身分識別的相關信息。 它也會保存使用者的相關信息,除非 Web 應用程式接受來自精靈應用程式的服務對服務呼叫。
以下是 C# 程式代碼範例,其會在用戶端使用適用於 .NET 的 Microsoft 驗證連結庫取得令牌之後,顯示呼叫 API 的用戶端(MSAL.NET):
var scopes = new[] {$"api://.../access_as_user"};
var result = await app.AcquireToken(scopes)
.ExecuteAsync();
httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
// Call the web API.
HttpResponseMessage response = await _httpClient.GetAsync(apiUri);
重要
用戶端應用程式會向 Web API 的 Microsoft 身分識別平台 要求持有人令牌。 API 是唯一應該驗證令牌並檢視其包含宣告的應用程式。 用戶端應用程式不應該嘗試檢查令牌中的宣告。
未來,Web API 可能需要加密令牌。 這項需求會防止可檢視取令牌的用戶端應用程式存取。
JwtBearer 組態
本節說明如何設定持有人令牌。
組態檔
只有在您想要接受來自單一租使用者 (企業營運應用程式) 的存取令牌時,才需要指定 TenantId
。 否則,它可以保留為 common
。 不同的值可以是:
- GUID (租使用者識別碼 = 目錄識別子)
common
可以是任何組織和個人帳戶organizations
可以是任何組織consumers
是 Microsoft 個人帳戶
{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"ClientId": "Enter_the_Application_(client)_ID_here",
"TenantId": "common"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
使用 Web API 的自訂應用程式識別碼 URI
如果您已接受 Azure 入口網站 建議的預設應用程式識別碼 URI,則不需要指定物件(請參閱應用程式識別碼 URI 和範圍)。 否則,請新增 Audience
屬性,其值為 Web API 的應用程式識別碼 URI。 這通常以 api://
開頭。
{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"ClientId": "Enter_the_Application_(client)_ID_here",
"TenantId": "common",
"Audience": "Enter_the_Application_ID_URI_here"
},
}
程式代碼初始化
在保存 [授權] 屬性的控制器動作上呼叫應用程式時,ASP.NET 並 ASP.NET Core 從 Authorization 標頭的持有人令牌擷取存取令牌。 存取令牌接著會轉送至 JwtBearer 中間件,此中間件會呼叫適用於 .NET 的 Microsoft IdentityModel Extensions。
Microsoft.Identity.Web
Microsoft 建議您在使用 ASP.NET Core 開發 Web API 時,使用 Microsoft.Identity.Web NuGet 套件。
Microsoft.Identity.Web 提供 ASP.NET Core、驗證中間件和適用於 .NET 的 Microsoft 驗證連結庫 (MSAL) 之間的黏附。 它可讓您更清楚、更健全的開發人員體驗,並運用 Microsoft 身分識別平台 和 Azure AD B2C 的強大功能。
適用於 .NET 6.0 的 ASP.NET
若要建立使用 Microsoft.Identity.Web 的新 Web API 專案,請使用 .NET 6.0 CLI 或 Visual Studio 中的項目範本。
Dotnet core CLI
# Create new web API that uses Microsoft.Identity.Web
dotnet new webapi --auth SingleOrg
Visual Studio - 若要在 Visual Studio 中建立 Web API 專案,請選取 [檔案>新>專案>] ASP.NET Core Web API。
.NET CLI 和 Visual Studio 專案範本都會建立類似 此代碼段的Program.cs 檔案。 請注意 Microsoft.Identity.Web
using 指示詞和包含驗證和授權的行。
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Identity.Web;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();