Identity Server 4 从入门到落地(十)—— 编写可配置的客户端和Web Api

前面的部分:
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"
  }
posted @ 2021-12-12 10:40  寻找无名的特质  阅读(1010)  评论(2编辑  收藏  举报