Identity Server 4 从入门到落地(十)—— 编写可配置的客户端和Web Api
前面的部分:
Identity Server 4 从入门到落地(一)—— 从域名n开始
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://域名/zhenl/IDS4Admin
客户端及web api示例代码的github地址:https://域名/zhenl/IDS4ClientDemo
前面的客户端和Web Api编写时,认证服务的地址等配置数据是在代码里写死的,在实际项目中这样肯定是不行的:我们不能因为认证服务的地址修改就重新修改和部署客户端和Web Api。另外在试验中我们也发现了很多不方便的地方,比如,每增加一类客户端,我们就需要修改Web Api,增加CORS的地址。因此,我们需要将这些配置数据转移到配置文件中进行维护。为此,我写了一个简单的扩展来帮助解决这个问题,项目代码地址:https://域名/zhenl/域名tityServer4ClientConfig
使用这个扩展很简单,首先在需要创建Identit Server 4客户端的项目中引入包域名tityServer4ClientConfig :
然后在域名中增加:
域名S4OpenIdConnect(域名iguration); //Added
这样就可以了,完整的代码如下:
var builder = 域名teBuilder(args);
// Add services to the container.
域名ontrollersWithViews();
域名S4OpenIdConnect(域名iguration); //Added
var app = 域名d();
// Configure the HTTP request pipeline.
if (!域名velopment())
{
域名xceptionHandler("/Home/Error");
}
域名taticFiles();
域名outing();
域名uthentication(); //增加的代码
域名uthorization();
域名ontrollerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}")
.RequireAuthorization(); //Added;
域名();
所有的配置项转移到域名中:
"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 = 域名teBuilder(args);
// Add services to the container.
域名ontrollers();
// Learn more about configuring Swagger/OpenAPI at https://域名/aspnetcore/swashbuckle
域名dentityServer4Api(域名iguration);//增加代码
域名ndpointsApiExplorer();
域名waggerGen();
var app = 域名d();
域名ors("cors");//增加代码
// Configure the HTTP request pipeline.
if (域名velopment())
{
域名wagger();
域名waggerUI();
}
域名uthentication();
域名uthorization(); //增加代码
域名ontrollers()
.RequireAuthorization("ApiScope");//增加代码
;
域名();
Web Api在域名中的配置项如下:
"IdentityServer4Api": {
"Authority": "http://localhost:4010",
"CorsOrgins": [
"https://localhost:7002"
],
"Policies": [
{
"Name": "ApiScope",
"RequireAuthenticatedUser": "true",
"Claims": [
{
"ClaimType": "scope",
"AllowValues": [ "myapi" ]
}
]
}
],
"RequireHttpsMetadata": "false"
}