前面的部分:
Identity Server 4 從入門到落地(一)—— 從IdentityServer4.Admin開始
Identity Server 4 從入門到落地(二)—— 理解授權碼模式
Identity Server 4 從入門到落地(三)—— 創建Web客戶端
認證服務和管理的github地址: https://github.com/zhenl/IDS4Admin
客戶端及web api示例代碼的github地址:https://github.com/zhenl/IDS4ClientDemo
前面我們創建了使用Identity Server 4進行認證的客戶端,現在創建受Identity Server 4認證服務保護的Web Api。在Visual Studio 2022中使用模板創建Asp.Net Core Web Api項目,不增加任何業務代碼,就使用缺省的示例。創建完成后,引入程序包microsoft.aspnetcore.authentication.jwtbearer,然后修改lanuchSettings.json,將項目設置為自啟動:
{
"profiles": {
"IDS4WebApi": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5153",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
接下來增加認證相關的代碼,這里使用的是.Net 6的結構,與傳統風格略有不同:
using Microsoft.IdentityModel.Tokens;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
//增加代碼
builder.Services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Authority = "http://localhost:4010";
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false
};
});
// adds an authorization policy to make sure the token is for scope 'api1'
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("ApiScope", policy =>
{
policy.RequireAuthenticatedUser();
policy.RequireClaim("scope", "myapi");
});
});
//增加完成
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()
.RequireAuthorization("ApiScope");//增加代碼
app.Run();
增加的代碼用注釋進行了標注。需要注意的幾個部分是:
- 認證服務器的地址不能寫錯
- 定義的ApiScope的名稱,需要在認證服務器進行配置,這里是myapi
- 由於認證服務器使用非SSL協議,需要增加選項options.RequireHttpsMetadata = false;
下面在認證服務器中增加Api資源和Api Scope:
到此,受保護的Web Api就完成了。可以為客戶端授權訪問myapi。下面我們改造前面的客戶端來訪問這個web api。
首先在前面的客戶端項目中增加IdentityModel程序包,然后在可訪問的scope中增加myapi:
options.Scope.Add("myapi");
然后在HomeController中增加訪問Web Api的代碼:
public async Task<IActionResult> GetApiData()
{
var auth = await HttpContext.AuthenticateAsync();
var token = auth.Properties.Items[".Token.access_token"];
var apiClient = new HttpClient();
apiClient.SetBearerToken(token);
var response = await apiClient.GetAsync("http://localhost:5153/WeatherForecast");
string result;
if (!response.IsSuccessStatusCode)
{
result = response.StatusCode.ToString();
}
else
{
var content = await response.Content.ReadAsStringAsync();
result = content;// JArray.Parse(content);
}
return Json(result);
}
不要忘了,在認證服務的客戶端定義中,為客戶端增加myapi的訪問權限:
如果從Visual Studio 中運行,需要同時啟動客戶端和Web Api,可以將解決方案設置為多項目啟動:
登錄后訪問https://localhost:7002/Home/GetApiData,結果如下:
以上示例的相關代碼可以從github中獲取: https://github.com/zhenl/IDS4ClientDemo