書接上回,我們已經搭建好了基於Identity Server 4的認證服務和管理應用(如果還沒有搭建,參看本系列前兩部分,相關代碼可以從github下載:https://github.com/zhenl/IDS4Admin )。
現在我們來創建Web客戶端。基本上可以按照Identity Server官網教程來: https://identityserver4.readthedocs.io/en/latest/quickstarts/2_interactive_aspnetcore.html 。只不過我使用的是.Net 6,代碼上有少許出入。
首先創建一個Asp.Net Core Web項目,使用MVC項目模板,在創建時選擇不需要身份認證。然后引入程序包 Microsoft.AspNetCore.Authentication.OpenIdConnect。
接下來修改Program.cs,.Net 6引入了簡潔模式,代碼看上去有些不同。
using System.IdentityModel.Tokens.Jwt;
var builder = WebApplication.CreateBuilder(args);
//增加的代碼
JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
options.Authority = "http://localhost:4010";
options.RequireHttpsMetadata = false;
options.ClientId = "myclient";
options.ClientSecret = "secret";
options.ResponseType = "code";
options.Scope.Add("openid");
options.Scope.Add("profile");
options.GetClaimsFromUserInfoEndpoint = true;
options.SaveTokens = true;
});
//增加結束
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication(); //增加的代碼
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}")
.RequireAuthorization(); //增加的代碼
app.Run();
增加的代碼進行了注釋。需要注意的是,由於我們的測試認證服務器運行在http://localhost:4010,沒有使用HTTPS協議,所以增加了options.RequireHttpsMetadata = false。
還需要修改lanuch.json中的代碼,將項目改變為自啟動項目,不依賴IIS Express:
{
"profiles": {
"IDS4Client": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7002;http://localhost:5002",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
最后,修改Index.cshtml,顯示用戶信息:
@{
ViewData["Title"] = "Home Page";
}
@using Microsoft.AspNetCore.Authentication
<h2>Claims</h2>
<dl>
@foreach (var claim in User.Claims)
{
<dt>@claim.Type</dt>
<dd>@claim.Value</dd>
}
</dl>
<h2>Properties</h2>
<dl>
@foreach (var prop in (await Context.AuthenticateAsync()).Properties.Items)
{
<dt>@prop.Key</dt>
<dd>@prop.Value</dd>
}
</dl>
客戶端就編寫完成了,然后使用管理應用(我這里是http://localhost:4003)向認證服務的數據庫中增加這個客戶端的定義。設置項很多,可以參考現有的管理客戶端進行設置,也可以克隆現有的客戶端進行修改。主要的設置是基本信息和認證注銷部分,特別注意別忘了設置客戶端密鑰,並且密鑰需要與客戶端代碼中的相同,還有就是允許作用域也要和代碼中的相同。這兩部分的截圖如下:
設置完成后,訪問這個客戶端http://localhost:7002,會重定位到認證服務器提示登錄,登錄后,會出現下面的界面:

同意確認后,回到我們需要訪問的界面:

最后,增加登出鏈接,將這個鏈接增加到_Layout.chstml中,在菜單代碼下面增加這個鏈接:
<ul class="navbar-nav">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Logout">Logout</a>
</ul>
簡化起見,我們在HomeController中增加登出代碼,很簡單:
public IActionResult Logout()
{
return SignOut("Cookies", "oidc");
}
到此,采用Identity Server 4進行認證管理的Web客戶端就初步搭建完成了。下一步,我們需要搭建一個受Identity Server 4 保護的Web Api。
上述代碼可以github下載: https://github.com/zhenl/IDS4ClientDemo,喜歡的話給個star。