IdentityServer4的使用说明
作者:互联网
ids4 全称:IdentityServer4 是专门为 .net core 而生产了一个中间件,目前是为了数据安全 做的鉴权中心。
第一步:创建一个空的core api 项目:当然你要健 core mvc 也可以了,但是没有必要,
第二步:引用 IdentityServer4。
第三步:添加中间件
需要注意一点:ConfigureServices里面添加的是:
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients());
Configure方法里面添加的是
app.UseIdentityServer();
其他的代码跟ids4无关
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services
.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryApiScopes(Config.ApiScopes)
.AddInMemoryClients(Config.GetClients());
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseIdentityServer();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
第四步 Config类的创建 这里整个类都复制出来,直接生产一个文件就可以使用了。
using IdentityServer4.Models;
namespace IdentityServer4.Test
{
public class Config
{
public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>()
{
new ApiResource("api", "My Api")
};
}
public static IEnumerable<Client> GetClients()
{
return new List<Client>()
{
new Client()
{
ClientId = "client",
AllowedGrantTypes = GrantTypes.ClientCredentials,
ClientSecrets =
{
new Secret("123456".Sha256())
},
AllowedScopes =
{
"api"
}
}
};
}
public static IEnumerable<ApiScope> ApiScopes =>
new ApiScope[] { new ApiScope("api") };
public static IEnumerable<IdentityResource> GetIdentityResources()
{
return new List<IdentityResource>
{
new IdentityResources.OpenId()
};
}
}
}
第五步:启动鉴权中心服务
该项目端口号自定义设置为 19128。所以访问是:http://localhost:19128/connect/token。
注意: connect/token 这个是固定不变的,是 ids4最近的方法,不是开发自定义的,所以只需要直接去用就可以了。
主要需要注意他的调用方式跟参数
1:post方式调用
2:参数 client_id,client_secret,grant_type
3:参数值:上面的参数 对应的值分别是 : 记得上面配置了config,这3个值就是上面的config里面配置的。
client_id 就是 ClientId ,但是在postman里面必须用 client_id 对应的值就是 client 了,这个自己设置。
client_secret 这个就是ClientSecrets 对应的值就是自定义的:123456。
grant_type 就是一个枚举了,AllowedGrantTypes 对应的值是 client_credentials。
虽然枚举是:GrantTypes.ClientCredentials,但是 传的实际值是 client_credentials。
调用接口如图:
这样就成功了。
以上就是整个鉴权中心服务,我们知道怎么获取 token了,但是不知道怎么用?
下一篇我将为大家带来ocelot网关!
因为ids4是专门为core而生的,所以他也同时继承到了ocelot网关里面了。
标签:app,说明,client,使用,new,Config,public,IdentityServer4 来源: https://blog.csdn.net/jccgg/article/details/121264055