Identity Server 4 從入門到落地(十)—— 編寫可配置的客戶端和Web Api

尋找無名的特質發表於2021-12-12

前面的部分:
Identity Server 4 從入門到落地(一)—— 從IdentityServer4.Admin開始
Identity Server 4 從入門到落地(二)—— 理解授權碼模式
Identity Server 4 從入門到落地(三)—— 建立Web客戶端
Identity Server 4 從入門到落地(四)—— 建立Web Api
Identity Server 4 從入門到落地(五)—— 使用Ajax 訪問 Web Api
Identity Server 4 從入門到落地(六)—— 簡單的單頁面客戶端
Identity Server 4 從入門到落地(七)—— 控制檯客戶端
Identity Server 4 從入門到落地(八)—— .Net Framework 客戶端
Identity Server 4 從入門到落地(九)—— 客戶端User和Role的解析

認證服務和管理的github地址: https://github.com/zhenl/IDS4Admin
客戶端及web api示例程式碼的github地址:https://github.com/zhenl/IDS4ClientDemo

前面的客戶端和Web Api編寫時,認證服務的地址等配置資料是在程式碼裡寫死的,在實際專案中這樣肯定是不行的:我們不能因為認證服務的地址修改就重新修改和部署客戶端和Web Api。另外在試驗中我們也發現了很多不方便的地方,比如,每增加一類客戶端,我們就需要修改Web Api,增加CORS的地址。因此,我們需要將這些配置資料轉移到配置檔案中進行維護。為此,我寫了一個簡單的擴充套件來幫助解決這個問題,專案程式碼地址:https://github.com/zhenl/ZL.IdentityServer4ClientConfig

使用這個擴充套件很簡單,首先在需要建立Identit Server 4客戶端的專案中引入包ZL.IdentityServer4ClientConfig :

然後在Program.cs中增加:

builder.Services.AddIS4OpenIdConnect(builder.Configuration); //Added

這樣就可以了,完整的程式碼如下:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

builder.Services.AddIS4OpenIdConnect(builder.Configuration); //Added


var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();

app.UseRouting();
app.UseAuthentication(); //增加的程式碼
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}")
    .RequireAuthorization(); //Added;

app.Run();

所有的配置項轉移到appsettings.json中:

  "IdentityServer4Client": {
    "Authority": "http://localhost:4010",
    "ClientId": "myclient",
    "ClientSecret": "secret",
    "ResponseType": "code",
    "SaveTokens": "true",
    "RequireHttpsMetadata": "false",
    "Scopes": [ "openid", "profile", "myapi" ],
    "JsonKeys": [
      {
        "ClaimType": "age"
      },
      {
        "ClaimType": "nickname",
        "Key": "nickname"
      },
      {
        "ClaimType": "mydefine",
        "Key": "mydefine"
      }
    ]
  }

Web Api的擴充套件使用類似,也是先引入程式包,然後修改程式碼:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddIdentityServer4Api(builder.Configuration);//增加程式碼

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();
app.UseCors("cors");//增加程式碼

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseAuthentication();
app.UseAuthorization(); //增加程式碼
app.MapControllers()
    .RequireAuthorization("ApiScope");//增加程式碼
;

app.Run();

Web Api在appsettings.json中的配置項如下:

  "IdentityServer4Api": {
    "Authority": "http://localhost:4010",
    "CorsOrgins": [
      "https://localhost:7002"
    ],
    "Policies": [
      {
        "Name": "ApiScope",
        "RequireAuthenticatedUser": "true",
        "Claims": [
          {
            "ClaimType": "scope",
            "AllowValues": [ "myapi" ]
          }
        ]
      }
    ],
    "RequireHttpsMetadata": "false"
  }

相關文章