IdnentiyServer-使用客户端凭据访问API
情景如下:一个客户端要访问一个api,不需要用户登录,但是又不想直接暴露api给外部使用,这时可以使用identityserver添加访问权限。
客户端通过clientid和secrect访问identitserver的Token Endpoint,获取accesstoken;
接着客户端再使用accesstoken作为头部验证访问webapi。(webapi已经添加了identityserver的相关验证)。
代码实现:其中 "http://localhost:5000"是identityserver地址,"http://localhost:5001"是api地址
identityserver:在identityserver添加api和客户端,如下所示:定义了一个api1资源,client客户端。client客户端指定为ClientCredentials(客户端凭据)模式,并允许其访问api1。
public class Config
{
// scopes define the API resources in your system
public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
new ApiResource("api1", "My API")
};
} // clients want to access resources (aka scopes)
public static IEnumerable<Client> GetClients()
{
// client credentials client
return new List<Client>
{
new Client
{
ClientId = "client",
AllowedGrantTypes = GrantTypes.ClientCredentials, ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedScopes = { "api1" }
}
};
}
}
在startup配置identityserver如下:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// configure identity server with in-memory stores, keys, clients and scopes
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients());
} public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} app.UseIdentityServer();
}
}
WebApi:在api添加identityserver的验证,代码如下,其中定义了同样的api名称,"http://localhost:5000"是identityserver的地址。
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvcCore()
.AddAuthorization()
.AddJsonFormatters(); services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options =>
{
options.Authority = "http://localhost:5000";
options.RequireHttpsMetadata = false; options.ApiName = "api1";
});
} public void Configure(IApplicationBuilder app)
{
app.UseAuthentication(); app.UseMvc();
}
}
添加一个需要验证的控制器:
[Route("[controller]")]
[Authorize]
public class IdentityController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
}
}
客户端:
这里使用里IdentityModel类库
实际请求如下:
1.获取accesstoken:http://localhost:5000/connect/token?client_id=client&client_secret=secret&grant_type=client_credentials&scope=api1
2.请求api1
http://localhost:5001/identity
Headers
Authorization:accesstoken
public class Program
{
public static void Main(string[] args) => MainAsync().GetAwaiter().GetResult(); private static async Task MainAsync()
{
//获取identitserver的各个端点地址
var disco = await DiscoveryClient.GetAsync("http://localhost:5000");
if (disco.IsError)
{
Console.WriteLine(disco.Error);
return;
}
//获取具有api1访问权限的accesstoken
var tokenClient = new TokenClient(disco.TokenEndpoint, "client", "secret");
var tokenResponse = await tokenClient.RequestClientCredentialsAsync("api1"); if (tokenResponse.IsError)
{
Console.WriteLine(tokenResponse.Error);
return;
} Console.WriteLine(tokenResponse.Json);
Console.WriteLine("\n\n");
//设置accesstoken为http请求头,并访问api1
var client = new HttpClient();
client.SetBearerToken(tokenResponse.AccessToken); var response = await client.GetAsync("http://localhost:5001/identity");
if (!response.IsSuccessStatusCode)
{
Console.WriteLine(response.StatusCode);
}
else
{
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(JArray.Parse(content));
}
}
}
ps:
1.这里默认的accesstoken为jwt格式,客户端访问api时,api只需要在启动的时候访问identity获取秘钥即可。若为referencetoken,客户端访问api时,api需要授权访问的都会再请求一次identityserver,,而且api必须设置秘钥,client设置AccessTokenType属性为Reference。
2.可自定义AccessTokenLifetime(token存活时间),默认是3600秒,即一小时
IdnentiyServer-使用客户端凭据访问API的更多相关文章
- asp.net core系列 54 IS4用客户端凭据保护API
一. 概述 本篇开始进入IS4实战学习,从第一个示例开始,该示例是 “使用客户端凭据保护API”,这是使用IdentityServer保护api的最基本场景.该示例涉及到三个项目包括:Identity ...
- 【IdentityServer4文档】- 使用客户端凭据保护 API
使用客户端凭据保护 API quickstart 介绍了使用 IdentityServer 保护 API 的最基本场景. 接下来的场景,我们将定义一个 API 和一个想要访问它的客户端. 客户端将在 ...
- 第9章 使用客户端凭据保护API - Identity Server 4 中文文档(v1.0.0)
快速入门介绍了使用IdentityServer保护API的最基本方案. 我们将定义一个API和一个想要访问它的客户端. 客户端将通过提供ClientCredentials在IdentityServer ...
- ASP.NET Core的身份认证框架IdentityServer4(7)- 使用客户端证书控制API访问
前言 今天(2017-9-8,写于9.8,今天才发布)一口气连续把最后几篇IdentityServer4相关理论全部翻译完了,终于可以进入写代码的过程了,比较累.目前官方的文档和Demo以及一些相关组 ...
- IdentityServer4(7)- 使用客户端认证控制API访问(客户端授权模式)
一.前言 本文已更新到 .NET Core 2.2 本文包括后续的Demo都会放在github:https://github.com/stulzq/IdentityServer4.Samples (Q ...
- .NET Core IdentityServer4实战 第一章-入门与API添加客户端凭据
内容:本文带大家使用IdentityServer4进行对API授权保护的基本策略 作者:zara(张子浩) 欢迎分享,但需在文章鲜明处留下原文地址. 本文将要讲述如何使用IdentityServer4 ...
- IdentityServer4[3]:使用客户端认证控制API访问(客户端授权模式)
使用客户端认证控制API访问(客户端授权模式) 场景描述 使用IdentityServer保护API的最基本场景. 我们定义一个API和要访问API的客户端.客户端从IdentityServer请求A ...
- Identity Server 4客户端认证控制访问API
项目源码: 链接:https://pan.baidu.com/s/1H3Y0ct8xgfVkgq4XsniqFA 提取码:nzl3 一.说明 我们将定义一个api和要访问它的客户端,客户端将在iden ...
- IdentityServer4之Client Credentials(客户端凭据许可)
IdentityServer4之Client Credentials(客户端凭据许可) 参考 项目创建:0_overview,1_client_credentials 概念:客户端凭据许可 认证服务端 ...
随机推荐
- Python基础知识当中容易混淆的几个知识点
在Python的基础知识当中,对于类实现可迭代功能有了一种新的方式,而这种方式则有别于我们学.NET等其他高级语言. 在Python当中,目前常用的有两种方式来实现这种迭代器的返回:__iter__ ...
- iOS 数据归档----温故而知新
#import "StudyViewController.h" #import "person.h" @interface StudyViewControlle ...
- weblogic 与项目jar冲突解决方案 ITsm部署
部署时出现找不到类itims*****IMOType 时删除 2个fvsd-res-ws-1.0.ja,itims-fvsd-res-sync.jar jar包 里面的DeviceInfoPort ...
- MySQL--REPLACE INTO与自增
##=====================================================================##测试环境:MySQL版本:MySQL 5.7.19复制 ...
- 在Docker容器中搭建MXNet/Gluon开发环境
在这篇文章中没有直接使用MXNet官方提供的docker image,而是从一个干净的nvidia/cuda镜像开始,一步一步部署mxnet需要的相关软件环境,这样做是为了更加细致的了解mxnet的运 ...
- mysql命令行创建表,插入表数据
create table t_hero( id int unsigned auto_increment primary key, name varchar(10) unique not null, a ...
- Python学习笔记【第十三篇】:Python网络编程一Socket基础
什么是⽹络 网络能把双方或多方连在一起的工具,即把数据从一方传递到另一方进行数据传递. 网络编程就是不同电脑上的软件能够进行数据传递.即进程间的通讯. 什么是TCP/IP协议 协议就是大家一起遵守的约 ...
- python Event_loop(事件循环)
由于GIL全局解释器锁的存在,意味着在任何一个时刻,只有一个线程处于执行状态. (1)执行栈: 因为python是单线程的,同一时间只能执行一个方法,所以当一系列的方法被依次调用的时候,python会 ...
- JavaScript笔记整理
整理一篇工作中的JavaScript脚本笔记,不定时更新,笔记来自网上资料或者自己经验归纳. (1) 获取Url绝对路径 function getUrlRelativePath() { var url ...
- Python - 调试Python代码的方法
调试(debug) 将可疑环节的变量逐步打印出来,从而检查哪里是否有错. 让程序一部分一部分地运行起来.从核心功能开始,写一点,运行一点,再修改一点. 利用工具,例如一些IDE中的调试功能,提高调试效 ...