IdentityServer4[3]:使用客户端认证控制API访问(客户端受权模式)

使用客户端认证控制API访问(客户端受权模式)

场景描述

使用IdentityServer保护API的最基本场景。html

咱们定义一个API和要访问API的客户端。客户端从IdentityServer请求AccessToken,而后访问对应的API。json

建立项目
  • IdentityServer的ASP.NET Core Web空项目,端口5000api

  • Api的ASP.NET Core Web API项目,端口5001浏览器

  • Client的控制台项目ide

5.png

IdentityServer准备工做

定义API资源工具

1.jpg

定义客户端post

TIM截图20190307150120.jpg

配置IdentityServer3d

TIM截图20190307163327.jpg

运行IdentityServer项目(自宿主)并在浏览器中输入地址:http://localhost:5000/.well-known/openid-configuration既能够看到IdentityServer的各类元数据信息,能够使用在线json格式化工具显示以下:code

TIM截图20190307152843.jpg

API准备

在API控制器上,增长[Authorize]特性(受权)视频

TIM截图20190307154700.jpg

startup增长以下代码:

TIM截图20190307154726.jpg

AddAuthentication将身份认证添加到DI,使用"Bearer"方案。AddIdentityServerAuthentication将IdentityServer Token认证处理程序添加到DI,供身份认证服务使用。配置提供Token的基地址为:"http://localhost:5000",不使用https。

若是此时使用postman访问:http://localhost:5001/api/values,则会获得401的结果

TIM截图20190307154552.jpg

建立客户端

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调用

TIM截图20190307163755.jpg

IdentityServer4 中文文档与实战

IdentityServer4 知多少

jessetalk视频教程