使用客户端认证控制API访问(客户端授权模式)
场景描述
使用IdentityServer保护API的最基本场景。
我们定义一个API和要访问API的客户端。客户端从IdentityServer请求AccessToken,然后访问对应的API。
创建项目
-
Core Web空项目,端口5000
-
Core Web API项目,端口5001
-
Client的控制台项目
IdentityServer准备工作
定义API资源
1.jpg定义客户端
TIM截图20190307150120.jpg配置IdentityServer
TIM截图20190307163327.jpg TIM截图20190307152843.jpgAPI准备
在API控制器上,增加[Authorize]特性(授权)
TIM截图20190307154700.jpgstartup增加如下代码:
TIM截图20190307154726.jpg 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