IdentityServer4之Client Credentials(客户端凭据许可)

参考

项目创建:0_overview1_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 authentication
AllowedGrantTypes = GrantTypes.ClientCredentials,
//Jwt = 0;Reference = 1支持撤销;
AccessTokenType = AccessTokenType.Reference,
// secret for authentication
ClientSecrets =
{
new Secret("secret".Sha256()),
new Secret("abc".Sha256())
},
// scopes that client has access to
AllowedScopes = { "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 metadata
Task<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 token
var 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 api
var 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: -continue
Host: localhost:
MS-ASPNETCORE-TOKEN: 08de58f6-58ee-4f05-8d95-3829dde6ae09
X-Forwarded-For: [::]:
X-Forwarded-Proto: http
Content-Length:
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每次(可配置缓存)会去认证服务器获取信息。参考

IdentityServer4之Client Credentials(客户端凭据许可)的更多相关文章

  1. asp.net core IdentityServer4 实现 Client credentials(客户端凭证)

    前言 OAuth 2.0默认四种授权模式(GrantType) 授权码模式(authorization_code) 简化模式(implicit) 密码模式(resource owner passwor ...

  2. IdentityServer4 之Client Credentials走起来

    前言 API裸奔是绝对不允许滴,之前专门针对这块分享了jwt的解决方案(WebApi接口裸奔有风险):那如果是微服务,又怎么解决呢?每一个服务都加认证授权也可以解决问题,只是显得认证授权这块冗余,重复 ...

  3. IdentityServer4之Resource Owner Password Credentials(资源拥有者密码凭据许可)

    IdentityServer4之Resource Owner Password Credentials(资源拥有者密码凭据许可) 参考 官方文档:2_resource_owner_passwords ...

  4. IdentityServer4 (1) 客户端授权模式(Client Credentials)

    写在前面 1.源码(.Net Core 2.2) git地址:https://github.com/yizhaoxian/CoreIdentityServer4Demo.git 2.相关章节 2.1. ...

  5. 基于 IdentityServer3 实现 OAuth 2.0 授权服务【客户端模式(Client Credentials Grant)】

    github:https://github.com/IdentityServer/IdentityServer3/ documentation:https://identityserver.githu ...

  6. IdentityServer4:IdentityServer4+API+Client实践OAuth2.0客户端模式(1)

    一.OAuth2.0 1.OAuth2.0概念 OAuth2.0(Open Authorization)是一个开放授权协议:第三方应用不需要接触到用户的账户信息(如用户名密码),通过用户的授权访问用户 ...

  7. 【IdentityServer4文档】- 使用客户端凭据保护 API

    使用客户端凭据保护 API quickstart 介绍了使用 IdentityServer 保护 API 的最基本场景. 接下来的场景,我们将定义一个 API 和一个想要访问它的客户端. 客户端将在 ...

  8. (转)基于OWIN WebAPI 使用OAuth授权服务【客户端模式(Client Credentials Grant)】

    适应范围 采用Client Credentials方式,即应用公钥.密钥方式获取Access Token,适用于任何类型应用,但通过它所获取的Access Token只能用于访问与用户无关的Open ...

  9. 基于OWIN WebAPI 使用OAuth授权服务【客户端模式(Client Credentials Grant)】

    适应范围 采用Client Credentials方式,即应用公钥.密钥方式获取Access Token,适用于任何类型应用,但通过它所获取的Access Token只能用于访问与用户无关的Open ...

随机推荐

  1. Python学习的相关文件链接

    1.如何用 Python 模糊搜索文件    用循环来实现逐个比对,素材链接:https://files.cnblogs.com/files/Lamfai/script_project1_files. ...

  2. 机器学习之--线性回归sigmoid函数分类

    import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import random #sigmoid函数 ...

  3. 逆向分析一款国外Blackjack Card Counter软件并附上License生成脚本

    没有学过逆向,一时兴起,搞了一下这个小软件,名为“逆向分析”,其实过程非常简单,难登大雅之堂,就当段子看吧.首先介绍一下背景吧.这是一款国外的Blackjack也就是21点算牌软件,我从来不玩牌的,机 ...

  4. navigator的一些冷知识

    { 监听屏幕旋转变化接口: orientationchange orientation.angle : 0 竖屏 , 90 向左横屏 , -90/270 向右横屏 , 180 倒屏 } screenO ...

  5. Azkaban日志中文乱码问题解决

    Azkaban作为LinkedIn开源的任务流式管理工具,在工作中很大程度上被用到.但是,由于非国人开发,对中文的支持性很不好.大多数情况下,会出现几种乱码现象: - 执行内置脚本生成log乱码 - ...

  6. python3.5.2库getpass

    getpass的功能是:允许隐式的输入字符串 import getpass _username='vigossr' _password='haha' username=input('username: ...

  7. Android滑动列表(拖拽,左滑删除,右滑完成)功能实现(1)

    场景: 近期做的TODO APP需要在主页添加一个功能,就是可以左滑删除,右滑完成.看了一下当前其他人做的例如仿探探式的效果,核心功能基本一样,但是和我预想的还是有少量区别,于是干脆自己重头学一遍如何 ...

  8. Python列表,字典和字符串操作

    列表: 列表:list, 也叫数组,表现[].特点:有角标,元素可以重复,有序的元素 例子:stus = ['王志华','乔美玲','乔美玲','王文文','feixiang']#中括号,这就是一个l ...

  9. VB读写进程的内存

    在窗体部分简单测试了ReadProcessMemory和WriteProcessMemory对另一个程序进程的读写. 由于临时项目变动,又不需要了,所以直接封类,删工程.以下代码没有一个函数经过测试, ...

  10. textarea--去掉空格的办法

    我在初次用到textarea多行文本框时,遇到的问题是:默认出现了两行空格,如图: 代码是(错误的写法): 最后才发现,原来是: textarea标签是需要写在同一行,不能换行,正确的写法: