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

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

场景描述

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

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

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

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

  • Client的控制台项目

5.png

IdentityServer准备工作

定义API资源

1.jpg

定义客户端

TIM截图20190307150120.jpg

配置IdentityServer

TIM截图20190307163327.jpg

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

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视频教程

原文地址:https://www.cnblogs.com/vigorous/p/10493949.html