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 概念:客户端凭据许可 认证服务端 ...
随机推荐
- linux 最为常用的命令
系统信息 arch 显示机器的处理器架构(1) uname -m 显示机器的处理器架构(2) uname -r 显示正在使用的内核版本 cat /proc/cpuinfo 显示CPU info的信息 ...
- Nginx 教程(1):基本概念
简介 嗨!分享就是关心!所以,我们愿意再跟你分享一点点知识.我们准备了这个划分为三节的<Nginx教程>.如果你对 Nginx 已经有所了解,或者你希望了解更多,这个教程将会对你非常有帮助 ...
- java 基础复习
最近准备阿里巴巴的面试,被提到需要一个比较好的java能力,因此花了点时间,再次把JAVA看了一遍,其中的某些重点记录下来,以便以后复习. (1)& 和&& 的区别 (2)排序 ...
- Android-Could not download kotlin-reflect.jar
在AndroidStudio中报以下错误: 错误详情: Could not download kotlin-reflect.jar (org.jetbrains.kotlin:kotlin-refle ...
- docker zabbix
1.zabbix-mysql 数据库 sudo docker pull zabbix/zabbix-server-mysql sudo docker run --name some-zabbix-se ...
- SpringDataJPA
看着自己弟弟在成都聚全家之力盘一套房, 看着自己二哥,在成都也为车贷房贷奔波劳累,身心俱惫, 生活不易啊,这个社会环境下,就像从数据库拿数据一样,只拿我们想要的,或许会活的滋润很多吧. 最近的这个项目 ...
- java处理数据库不支持的emoji表情符
一般数据库的编码是utf8,utf8是不支持存储表情符的,当存入的微信昵称带有表情符时就会出现乱码情况,有两种解决方法: 1.mysql数据库升级到5.5版本以上,utf8改为utf8mb4,utf8 ...
- Javascript高级编程学习笔记(29)—— BOM(3)location对象
在JS中location是一个神奇的对象 它既是window对象的属性,也是document对象的属性 它的作用主要在于保存当前文档页面的信息,以及将 url 解析为独立的片段 location对象属 ...
- 卷积神经网络CNN的原理(三)---代码解析
卷积神经网络在几个主流的神经网络开源架构上面都有实现,我这里不是想实现一个自己的架构,主要是通过分析一个最简单的卷积神经网络实现代码,来达到进一步的加深理解卷积神经网络的目的. 笔者在github上找 ...
- 《JQuery技术内幕》读书笔记——自调用匿名函数剖析
Javascript语言中的自调用匿名函数格式如下: (function(){ //do somethings })(); 它还有另外两种等价写法如下: //等价写法一 (function(){ // ...