使用IdentityServer保护API的最基本场景。html
咱们定义一个API和要访问API的客户端。客户端从IdentityServer请求AccessToken,而后访问对应的API。json
IdentityServer的ASP.NET Core Web空项目,端口5000api
Api的ASP.NET Core Web API项目,端口5001浏览器
Client的控制台项目ide
定义API资源工具
定义客户端post
配置IdentityServer3d
运行IdentityServer项目(自宿主)并在浏览器中输入地址:http://localhost:5000/.well-known/openid-configuration既能够看到IdentityServer的各类元数据信息,能够使用在线json格式化工具显示以下:code
在API控制器上,增长[Authorize]特性(受权)视频
startup增长以下代码:
AddAuthentication将身份认证添加到DI,使用"Bearer"方案。AddIdentityServerAuthentication将IdentityServer Token认证处理程序添加到DI,供身份认证服务使用。配置提供Token的基地址为:"http://localhost:5000",不使用https。
若是此时使用postman访问:http://localhost:5001/api/values,则会获得401的结果
IdentityModel 包括用于发现 IdentityServer 各个终结点(EndPoint)的客户端库。这样只须要知道 IdentityServer 的地址 - 能够从元数据中读取实际的各个终结点地址:
var client = new HttpClient(); var disdoc = client.GetDiscoveryDocumentAsync("http://localhost:5000").Result; if (disdoc.IsError) { Console.WriteLine(disdoc.Error); }
获取token
var tokenResponse = client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest { Address = disdoc.TokenEndpoint, ClientId = "client", ClientSecret = "secret", Scope = "api1" }).Result; if (tokenResponse.IsError) { Console.WriteLine(tokenResponse.Error); } else { Console.WriteLine(tokenResponse.Json); }
调用API
HttpClient httpClient = new HttpClient(); httpClient.SetBearerToken(tokenResponse.AccessToken); var response = httpClient.GetAsync("http://localhost:5001/api/values").Result; if (response.IsSuccessStatusCode) { Console.WriteLine(response.Content.ReadAsStringAsync().Result); }
使用postman调用