文章目录
本篇幅所涉及的内容比较多,请园友有耐心的品味下去。
1、IdentityServer介绍
IdentityServer4 是asp.netcore 的OpenID Connect和OAuth 2.0框架。官方文档:http://docs.identityserver.io/en/latest/
我主要进行对自己所做的进行总结,不会介绍很多的理论类容。
2、建立IdentityServer
2.1 安装IdentityServer4
可以使用PS进行命令安装: Install-Package IdentityServer4。也可以在Nuget管理中心进行搜索安装。
2.2 定义配置中心
网上很多都是使用的TestUser进行的测试,我这个案例中使用sqlserver持久化进行验证,对于用户这块我后面详细介绍。(要是觉得麻烦那么也可以使用TestUser和)
2.2.1 定义Client
可以查看 官方文档–Client 进行了解Client相关知识。
public class InMemoryConfiguration
{
public static IEnumerable<Client> GetAllClients()
{
return new[]
{
//采用密码模式
new Client
{
ClientId = "api.service1",
ClientSecrets = new [] {
new Secret("secret".Sha256()) },
AllowedGrantTypes = GrantTypes.ResourceOwnerPasswordAndClientCredentials,
AllowedScopes = new [] {
"service1",
},
//支持刷新token
AllowOfflineAccess=true,
//toke过期时间。默认一小时
//AccessTokenLifetime=60,
//滑动刷新token的时间。默认一天。
//SlidingRefreshTokenLifetime=60,
//刷新token的模式,固定刷新时间和滑动刷新时间
//RefreshTokenExpiration=TokenExpiration.Sliding,
//详情文档:https://identityserver4-zh-cn.readthedocs.io/zh_CN/release/topics/refresh_tokens.html
},
//采用客户端模式
new Client
{
ClientId = "api.service2",
ClientSecrets = new [] {
new Secret("secret".Sha256()) },
AllowedGrantTypes = GrantTypes.ClientCredentials,
AllowedScopes = new [] {
"service2",
},
}
};
}
}
2.2.2 定义ApiResource
可以查看 官方文档–ApiResouce 进行了解ApiResouce相关知识。
public class InMemoryConfiguration
{
public static IEnumerable<ApiResource> GetAllResources()
{
return new[]
{
//向Cliam中添加Role、Email。这样在获取HttpContext.User.Cliam时才能获取到role、email
new ApiResource("service1", "微服务架构设计,Service1",new List<string>{
JwtClaimTypes.Role,
JwtClaimTypes.Email,
}),
new ApiResource("service2", "微服务架构设计,Service2",new List<string>{
JwtClaimTypes.Role,
JwtClaimTypes.Email,
})
};
}
}
2.2.3定义IdentityResource
可以查看 官方文档–IdentityResource 进行了解IdentityResource相关知识。
public class InMemoryConfiguration
{
public static IEnumerable<IdentityResource> GetIdentityResources()
{
//定义支持的资源类型。SuportScope的类型
return new List<IdentityResource>
{
new IdentityResources.OpenId(),
new IdentityResources.Profile()