IdentityServer4之Client Credentials(客户端凭据许可)
IdentityServer4之Client Credentials(客户端凭据许可)
参考
项目创建:0_overview,1_client_credentials
概念:客户端凭据许可
认证服务端配置
认证服务ApiResource配置
new ApiResource("api1", "api项目 一") {ApiSecrets = { new Secret("api1pwd".Sha256()) } },
认证服务Client配置
//client credentials client new Client {ClientId = "client",// no interactive user, use the clientid/secret for authenticationAllowedGrantTypes = GrantTypes.ClientCredentials, //Jwt = 0;Reference = 1支持撤销;AccessTokenType = AccessTokenType.Reference,// secret for authenticationClientSecrets ={new Secret("secret".Sha256()),new Secret("abc".Sha256())},// scopes that client has access toAllowedScopes = { "api1" } },
认证服务Startup配置
// configure identity server with in-memory stores, keys, clients and scopes services.AddIdentityServer().AddDeveloperSigningCredential().AddInMemoryApiResources(Config.GetApiResources()).AddInMemoryClients(Config.GetClients());
配置完成启动访问http://localhost:5000/.well-known/openid-configuration
资源服务Api配置
资源服务器Startup配置
services.AddMvcCore().AddAuthorization().AddJsonFormatters();services.AddAuthentication("Bearer").AddIdentityServerAuthentication(options =>{options.Authority = "http://localhost:5000";options.RequireHttpsMetadata = false;options.ApiName = "api1"; options.ApiSecret = "api1pwd"; //对应ApiResources中的密钥});
添加接口
[Route("[controller]")] [Authorize] public class IdentityController : ControllerBase {[HttpGet]public IActionResult Get(){var info = from c in User.Claims select new { c.Type, c.Value };var list = info.ToList();list.Add(new { Type = "api1返回", Value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") });return new JsonResult(list);} }
Client客户端
客户端与授权服务器进行身份验证并向令牌端点请求访问令牌。
授权服务器对客户端进行身份验证,如果有效,颁发访问令牌。
//credentials client private void btnAuth_Click(object sender, EventArgs e) {// discover endpoints from metadataTask<DiscoveryResponse> discoTask = DiscoveryClient.GetAsync(txtCCAuthSer.Text);discoTask.Wait();var disco = discoTask.Result;if (disco.IsError){MessageBox.Show(disco.Error, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);txtCCResult.Text = string.Empty;txtAccessToken.Text = string.Empty;return;}// request tokenvar tokenClient = new TokenClient(disco.TokenEndpoint, txtCCClient.Text, txtCCSecret.Text);Task<TokenResponse> tokenTask = tokenClient.RequestClientCredentialsAsync(txtCCScopes.Text);tokenTask.Wait();var tokenResponse = tokenTask.Result;if (tokenResponse.IsError){MessageBox.Show(tokenResponse.Error, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);txtCCResult.Text = string.Empty;txtAccessToken.Text = string.Empty;return;}txtCCResult.Text = tokenResponse.Json.ToString();txtAccessToken.Text = tokenResponse.AccessToken; }
调用Api
private void btnCallApi_Click(object sender, EventArgs e) {// call apivar client = new HttpClient();client.SetBearerToken(txtAccessToken.Text);var responseTask = client.GetAsync(txtCCApiUrl.Text);responseTask.Wait();var response = responseTask.Result;if (!response.IsSuccessStatusCode){MessageBox.Show(response.StatusCode.ToString(), "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);txtApiResult.Text = string.Empty;}else{var contentTask = response.Content.ReadAsStringAsync();contentTask.Wait();var content = contentTask.Result;txtApiResult.Text = JArray.Parse(content).ToString();} }
获取token过程解析
Jwt形式获取access_token
通过IdentityModel发送请求
监听请求数据
客户端身份验证两种方式
1、Authorization: Basic czZCaGRSa3F0Mzo3RmpmcDBaQnIxS3REUmJuZlZkbUl3。
POST /connect/token HTTP/1.1 Connection: Keep-Alive Content-Type: application/x-www-form-urlencoded Accept: application/json Authorization: Basic Y2xpZW50OnNlY3JldA== Expect: 100-continue Host: localhost:5000 MS-ASPNETCORE-TOKEN: 08de58f6-58ee-4f05-8d95-3829dde6ae09 X-Forwarded-For: [::1]:12112 X-Forwarded-Proto: http Content-Length: 40 grant_type=client_credentials&scope=api1
2、client_id(客户端标识),client_secret(客户端秘钥)。
Reference形式获取access_token
将client的AccessTokenType设置为1
再次获取的access_token不包含Claim信息。
此时获取的access_token(加密后)对应PersistedGrants表中的key
调用Api资源服务过程解析
Jwt形式获取access_token调用Api
监听请求数据
api资源服务验证Jwt形式token会去认证服务器获取一次配置信息。
Reference形式获取access_token调用Api
监听请求数据
api资源服务验证Reference形式token每次(可配置缓存)会去认证服务器获取信息。参考
转载于:https://www.cnblogs.com/ddrsql/p/7887083.html
IdentityServer4之Client Credentials(客户端凭据许可)相关推荐
- IdentityServer4 之Client Credentials走起来
前言 API裸奔是绝对不允许滴,之前专门针对这块分享了jwt的解决方案(WebApi接口裸奔有风险):那如果是微服务,又怎么解决呢?每一个服务都加认证授权也可以解决问题,只是显得认证授权这块冗余,重复 ...
- radmin提示授权码过期_IdentityServer4 客户端授权模式(Client Credentials)
(给DotNet加星标,提升.Net技能) 转自:朝闲cnblogs.com/Zing/p/13361386.html 前言 1.源码(.NET Core 2.2) git地址:https://git ...
- Identity Server 4 原理和实战(完结)_建立Identity Server 4项目,Client Credentials 授权实例...
创建项目 dotnet new -i IdentityServer4.Templates 多出来的这些模板 adminUI用来测试,想要用再生产环境,需要交钱 结合core的 Identity来使用 ...
- IdnentiyServer-使用客户端凭据访问API
情景如下:一个客户端要访问一个api,不需要用户登录,但是又不想直接暴露api给外部使用,这时可以使用identityserver添加访问权限. 客户端通过clientid和secrect访问iden ...
- OAuth2.0学习(1-7)授权方式4-客户端模式(Client Credentials Grant)
授权方式4-客户端模式(Client Credentials Grant) 客户端模式(Client Credentials Grant)指客户端以自己的名义,而不是以用户的名义,向"服务提 ...
- 在ASP.NET中基于Owin OAuth使用Client Credentials Grant授权发放Token
OAuth真是一个复杂的东东,即使你把OAuth规范倒背如流,在具体实现时也会无从下手.因此,Microsoft.Owin.Security.OAuth应运而生(它的实现代码在Katana项目中),帮 ...
- 创建TLS 客户端凭据时发生严重错误。内部错误状态为 10013。处理记录
某天用Adobe Media Encoder 2022给视频压缩转码时出现蓝屏,重新开机后查找系统日志,最后的报错是[创建 TLS 客户端 凭据时发生严重错误.内部错误状态为 10013.] 让我大吃 ...
- skywalking原理_SkyWalking 源码分析 —— Collector Client Component客户端组件
摘要: 原创出处 http://www.iocoder.cn/SkyWalking/collector-client-component/「芋道源码」欢迎转载,保留摘要,谢谢! 本文主要基于 SkyW ...
- 利用Fiddler模拟通过Dynamics 365的OAuth 2 Client Credentials认证后调用Web API
微软动态CRM专家罗勇 ,回复337或者20190521可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me. 配置Dynamics 365 & PowerApps 支 ...
- 【Spring Boot】Spring Boot 2.x + Spring Security OAuth2 2.3.3 出现 bad client credentials 错误的踩坑记录
环境: spring boot 2.0.4.RELEASE spring security oauth 2.3.3.RELEASE OAuth2的配置 @Configuration @EnableAu ...
最新文章
- 无限的hypotheses 变成有限的dichotomies
- C/C++ 位操作 总结
- mysql 变量作用_MySQL变量的用法
- Warning: Missing charsets in String to FontSet conversion
- 【转】Scala: Example use for early definition / early initializer / pre-initialized fields
- ES9新特性_ES9正则扩展-反向断言---JavaScript_ECMAScript_ES6-ES11新特性工作笔记055
- 微信小程序区分分享到群和好友
- Subversive-connectors 下载地址
- 防范蠕虫式勒索软件病毒攻击的安全预警通告
- Nginx支持ipv6
- Android端的新浪微博论文,android新浪微博客户端开发毕业论文.doc
- Qt中系统屏幕键盘打开与关闭
- 中科大自主招生2018年笔试数学
- httpwatch使用
- 关于 Android O 的 treble/hidl
- JS设计模式初识(七)-组合模式
- 类加载及执行子系统的案例分析
- @JsonFormat将时间字符串2021-02-25T15:32:54+08:00解析成date
- 离散傅里叶变换的算法实现
- 前端练手案例之日历(原生)一