1.创建鉴权中心 MicService.AuthCenter
新建一个WebApi项目
IdentityServer4配置
(1)引入IdentityServer4的Nuget包

(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

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

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

其中AuthIndex增加了鉴权校验,返回401

(2)从鉴权中心7002中获取Token:
访问localhost:7002/connect/token

(3)带上Token,重新访问AuthIndex

(4)把Token放入请求头Head中

(5)和GateWay整合
====待续====
以上,仅用于学习和总结!