1.创建鉴权中心 MicService.AuthCenter
新建一个WebApi项目
IdentityServer4配置
(1)引入IdentityServer4的Nuget包
![](https://img2020.cnblogs.com/blog/783110/202012/783110-20201223110806361-234512930.png)
(2)客户端模式配置 AuthConfig.cs
public class AuthConfig { public static IEnumerable<ApiResource> GetAPIResource() { return new[] { new ApiResource("UserApi","获取API") }; } public static IEnumerable<Client> GetClients() { return new[] { new Client { ClientId = "MicServiceAuthID",//客户端惟一标识 ClientSecrets = new [] { new Secret("MicServiceAuthID".Sha256()) },//客户端密码,进行了加密 AllowedGrantTypes=GrantTypes.ClientCredentials, AllowedScopes=new []{ "UserApi"} } }; } }
(3)配置Startup.cs
app.UseIdentityServer();//添加认证中间件
services.AddIdentityServer() .AddDeveloperSigningCredential()//默认的开发者证书 .AddInMemoryClients(InitConfig.GetClients()) .AddInMemoryApiResources(InitConfig.GetApiResources());
(4)启动
dotnet MicService.AuthCenter.dll --urls="http://*:7002" --port=7002
![](https://img2020.cnblogs.com/blog/783110/202012/783110-20201223112120079-246634015.png)
2.创建客户端 MicService.AuthClient
(1)引入IdentityServer4的Nuget包
(2)配置Startup.cs
app.UseAuthentication();//添加鉴权
services.AddAuthentication("Bearer") .AddIdentityServerAuthentication(options => { options.Authority = "http://localhost:7002"; options.ApiName = "UserApi"; options.RequireHttpsMetadata = false; });
(3)启动
dotnet MicService.AuthClient.dll --urls="http://*:8002" --port=8002
![](https://img2020.cnblogs.com/blog/783110/202012/783110-20201223112406553-2057314034.png)
3.Postman验证
[HttpGet] [Route("Index")] public IActionResult Index() { return new JsonResult(new { message="this is Index", Time=DateTime.Now.ToString() }); } [Authorize] [HttpGet] [Route("Index")] public IActionResult AuthIndex() { return new JsonResult(new { message = "this is AuthIndex", Time = DateTime.Now.ToString() }); }
(1)访问localhost:8002的Index和AuthIndex
![](https://img2020.cnblogs.com/blog/783110/202012/783110-20201223112734812-1120845420.png)
其中AuthIndex增加了鉴权校验,返回401
![](https://img2020.cnblogs.com/blog/783110/202012/783110-20201223112815726-1312249345.png)
(2)从鉴权中心7002中获取Token:
访问localhost:7002/connect/token
![](https://img2020.cnblogs.com/blog/783110/202012/783110-20201223112921905-1110824989.png)
(3)带上Token,重新访问AuthIndex
![](https://img2020.cnblogs.com/blog/783110/202012/783110-20201223113313146-777253009.png)
(4)把Token放入请求头Head中
![](https://img2020.cnblogs.com/blog/783110/202012/783110-20201223113408893-307745801.png)
(5)和GateWay整合
====待续====
以上,仅用于学习和总结!