要学习IdentityServer,需要了解下基于Token的验证体系,其中涉及到Token, OAuth&OpenID,JWT,协议规范等。
如图过程,
二. IdentityServer简单介绍
IdentityServer4 是一个基于OpenID Connect和OAuth 2.0的针对ASP.NET Core 2.0的框架,以中间件的形式存在。
通常你可以构建(或重新使用)包含登录和注销页面的应用程序,IdentityServer中间件会向其添加必要的协议头,以便客户端应用程序可以使用这些标准协议与其对话。
我们可以用IdentityServer来做什么?
身份验证服务:官方认证的OpenID Connect实现
单点登录/注销(SSO)
访问受控的API : 为不同的客户提供访问API的令牌,比如:MVC网站、SPA、Mobile APP等
...等等
三.简单项目示例先列出目录结构,以及创建顺序,来方便阅读
IdentityServerDemo --> APIService1和APIService2 --> MVCClient
其中,处MVCClient是asp.net core web mvc项目外,其他都是asp.net core web api 项目
创建名为IdentityServerDemo的认证服务1. 创建一个asp.net core web api项目:IdentityServerDemo。
注意,不要设置HTTPS,否则后面使用postman测试时,会no response
2. 添加InMemoryConfiguration
public class InMemoryConfiguration { public static IConfiguration Configuration { get; set; } /// <summary> /// Define which APIs will use this IdentityServer /// </summary> /// <returns></returns> public static IEnumerable<ApiResource> GetApiResources() { return new[] { new ApiResource("clientservice", "CAS Client Service"), new ApiResource("productservice", "CAS Product Service"), new ApiResource("agentservice", "CAS Agent Service") }; } /// <summary> /// Define which Apps will use thie IdentityServer /// </summary> /// <returns></returns> public static IEnumerable<Client> GetClients() { return new[] { new Client { ClientId = "client.api.service", ClientSecrets = new [] { new Secret("clientsecret".Sha256()) }, AllowedGrantTypes = GrantTypes.ResourceOwnerPasswordAndClientCredentials, AllowedScopes = new [] { "clientservice" } }, new Client { ClientId = "product.api.service", ClientSecrets = new [] { new Secret("productsecret".Sha256()) }, AllowedGrantTypes = GrantTypes.ResourceOwnerPasswordAndClientCredentials, AllowedScopes = new [] { "clientservice", "productservice" } }, new Client { ClientId = "agent.api.service", ClientSecrets = new [] { new Secret("agentsecret".Sha256()) }, AllowedGrantTypes = GrantTypes.ResourceOwnerPasswordAndClientCredentials, AllowedScopes = new [] { "agentservice", "clientservice", "productservice" } } }; } /// <summary> /// Define which uses will use this IdentityServer /// </summary> /// <returns></returns> public static IEnumerable<TestUser> GetUsers() { return new[] { new TestUser { SubjectId = "10001", Username = "test1@hotmail.com", Password = "test1password" }, new TestUser { SubjectId = "10002", Username = "test2@hotmail.com", Password = "test2password" }, new TestUser { SubjectId = "10003", Username = "test3@hotmail.com", Password = "test3password" } }; } }