项目结构
首先创建3个项目,这3个项目将做为我们学习 IdentityServer4 的基础项目,项目框架全部使用 .NET CORE 3.1。
端口约定如下:
MicroShell.IdentityServer4.Server : 5000
MicroShell.IdentityServer4.Api : 5001
MicroShell.IdentityServer4.Mvc : 5002
搭建 IdentityServer4 认证中心
添加依赖包
在项目 MicroShell.IdentityServer4.Server 中添加 Nuget 包:IdentityServer4,笔者使用的是 4.1.2 版本。
1 |
|
添加 IdentityServer 服务
ConfigureServices 方法中添加 IdentityServer 的依赖服务。
定义 Client
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
定义 ApiScope
1 2 3 4 5 6 7 |
|
做为快速入门篇,遵循一切从简的原则, Client 、签名都使用内存持久化模型,数据库持久化我们放到后面去讲。 准备好 Client 和 ApiScope 后开始注入它们的依赖服务。
1 2 3 4 5 |
|
注入 IdentityServer 中间件
Configure 方法中注入 IdentityServer 中间件。
1 2 3 |
|
使用 PostMan 测试
WebApi 集成 IdentityServer4 认证中心
添加依赖包
在项目 MicroShell.IdentityServer4.Api 中添加 Nuget 包:IdentityServer4.AccessTokenValidation,笔者使用的是 3.0.1 版本。
1 |
|
添加认证服务
在 ConfigureServices 方法中添加认证服务。
1 2 3 4 5 6 7 8 9 10 |
|
添加认证和授权中间件
在 Configure 方法中添加中间件。
1 2 3 4 5 6 7 |
|
创建需要授权的 Controller
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
使用 PostMan 测试
结尾
入门篇我们使用的 Client 是 ClientCredentials(客户端凭证模式),该模式因为没有用户参与,不适合 MVC 项目场景,所以笔者省略了 MVC 项目下的集成。