IdentityServer4 自定义授权模式
IdentityServer4除了提供常规的几种授权模式外(AuthorizationCode、ClientCredentials、Password、RefreshToken、DeviceCode),还提供了可以拓展的授权模式,下面就根据源码简单说下IdentityServer4是如何实现自定义授权模式的。
一、查看IdentityServer4自定义授权模式源码
当用户请求 connect/token 地址时,会执行TokenRequestValidator类的ValidateRequestAsync方法,在ValidateRequestAsync方法中根据GrantTypes类型调用不同的Validate方法,如下:
public async Task<TokenRequestValidationResult> ValidateRequestAsync(NameValueCollection parameters, ClientSecretValidationResult clientValidationResult)
{
//去掉了部分代码。。。 _validatedRequest.GrantType = grantType; switch (grantType)
{
case OidcConstants.GrantTypes.AuthorizationCode:
return await RunValidationAsync(ValidateAuthorizationCodeRequestAsync, parameters);
case OidcConstants.GrantTypes.ClientCredentials:
return await RunValidationAsync(ValidateClientCredentialsRequestAsync, parameters);
case OidcConstants.GrantTypes.Password:
return await RunValidationAsync(ValidateResourceOwnerCredentialRequestAsync, parameters);
case OidcConstants.GrantTypes.RefreshToken:
return await RunValidationAsync(ValidateRefreshTokenRequestAsync, parameters);
case OidcConstants.GrantTypes.DeviceCode:
return await RunValidationAsync(ValidateDeviceCodeRequestAsync, parameters);
default:
return await RunValidationAsync(ValidateExtensionGrantRequestAsync, parameters);
}
}
自定义的授权模式会进入 ValidateExtensionGrantRequestAsync 方法 ,方法中会做一些简单的验证,然后调用 _extensionGrantValidator.ValidateAsync 方法,_extensionGrantValidator.ValidateAsync方法实现如下:
public class ExtensionGrantValidator
{
private readonly ILogger _logger;
private readonly IEnumerable<IExtensionGrantValidator> _validators;//可以注入多个自定义授权类,用集合保存 /// <summary>
/// Initializes a new instance of the <see cref="ExtensionGrantValidator"/> class.
/// </summary>
/// <param name="validators">The validators.</param>
/// <param name="logger">The logger.</param>
public ExtensionGrantValidator(IEnumerable<IExtensionGrantValidator> validators, ILogger<ExtensionGrantValidator> logger)
{
if (validators == null)
{
_validators = Enumerable.Empty<IExtensionGrantValidator>();
}
else
{
//把注入的自定义授权类放入集合中
_validators = validators;
} _logger = logger;
} /// <summary>
/// 得到所有可用的自定义授权类型
/// </summary>
/// <returns></returns>
public IEnumerable<string> GetAvailableGrantTypes()
{
return _validators.Select(v => v.GrantType);
} /// <summary>
/// Validates the request.
/// </summary>
/// <param name="request">The request.</param>
/// <returns></returns>
public async Task<GrantValidationResult> ValidateAsync(ValidatedTokenRequest request)
{
//根据用户请求的GrantType获取自定义授权类
var validator = _validators.FirstOrDefault(v => v.GrantType.Equals(request.GrantType, StringComparison.Ordinal)); if (validator == null)
{
_logger.LogError("No validator found for grant type");
return new GrantValidationResult(TokenRequestErrors.UnsupportedGrantType);
} try
{
_logger.LogTrace("Calling into custom grant validator: {type}", validator.GetType().FullName); var context = new ExtensionGrantValidationContext
{
Request = request
};
//执行验证方法,这里执行的就是我们自定义授权的验证方法
await validator.ValidateAsync(context);
return context.Result;
}
catch (Exception e)
{
_logger.LogError(, e, "Grant validation error: {message}", e.Message);
return new GrantValidationResult(TokenRequestErrors.InvalidGrant);
}
}
}
二、实现自定义授权
比如我们想实现短信登录,就可以自定义一个授权类型 SMSGrantType
1、创建自定义授权类 SMSGrantValidator ,实现IExtensionGrantValidator接口
public class SMSGrantValidator : IExtensionGrantValidator
{
public string GrantType => ExtensionGrantTypes.SMSGrantType; public Task ValidateAsync(ExtensionGrantValidationContext context)
{
var smsCode = context.Request.Raw.Get("smsCode");
var phoneNumber = context.Request.Raw.Get("phoneNumber"); if (string.IsNullOrEmpty(smsCode) || string.IsNullOrEmpty(phoneNumber))
{
context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant);
} if (phoneNumber == "" && smsCode == "")
{
List<Claim> claimList = new List<Claim>();
claimList.Add(new Claim("userID", "")); context.Result = new GrantValidationResult(
subject: phoneNumber,
authenticationMethod: ExtensionGrantTypes.SMSGrantType,
claims: claimList);
}
else
{
context.Result = new GrantValidationResult(
TokenRequestErrors.InvalidGrant,
"短信码错误!"
);
}
return Task.FromResult(); }
}
2、在Startup中注入SMSGrantValidator
services.AddIdentityServer()
//配置证书
.AddDeveloperSigningCredential()
//配置API资源
.AddInMemoryApiResources(Config.GetApis())
//配置身份资源
.AddInMemoryIdentityResources(Config.GetIdentityResources())
//预置Client
.AddInMemoryClients(Config.GetClients())
//自定义登录返回信息
.AddProfileService<ProfileService>()
//添加Password模式下用于自定义登录验证
.AddResourceOwnerValidator<ResourceOwnerPasswordValidator>()
//添加自定义授权模式
.AddExtensionGrantValidator<SMSGrantValidator>();
3、配置Client
//自定义短信验证模式
new Client
{
ClientId = "sms",
ClientName = "sms",
ClientSecrets = { new Secret("".Sha256()) },
AccessTokenLifetime = *,//单位s
AllowedGrantTypes = new[] {ExtensionGrantTypes.SMSGrantType}, //一个 Client 可以配置多个 GrantType
SlidingRefreshTokenLifetime = ,
AllowOfflineAccess = true,
AllowedScopes = new List<string>
{
"FrameworkAPI",//对应webapi里面的scope配置
StandardScopes.OfflineAccess,
StandardScopes.OpenId,
StandardScopes.Profile
}
}
用postman测试,返回token,测试成功

IdentityServer4 自定义授权模式的更多相关文章
- Asp.Net Core 中IdentityServer4 授权中心之自定义授权模式
一.前言 上一篇我分享了一篇关于 Asp.Net Core 中IdentityServer4 授权中心之应用实战 的文章,其中有不少博友给我提了问题,其中有一个博友问我的一个场景,我给他解答的还不够完 ...
- IdentityServer4(客户端授权模式)
1.新建三个项目 IdentityServer:端口5000 IdentityAPI:端口5001 IdentityClient: 2.在IdentityServer项目中添加IdentityServ ...
- OAuth + Security - 6 - 自定义授权模式
我们知道OAuth2的官方提供了四种令牌的获取,简化模式,授权码模式,密码模式,客户端模式.其中密码模式中仅仅支持我们通过用户名和密码的方式获取令牌,那么我们如何去实现一个我们自己的令牌获取的模式呢? ...
- 认证授权:IdentityServer4 - 各种授权模式应用
前言: 前面介绍了IdentityServer4 的简单应用,本篇将继续讲解IdentityServer4 的各种授权模式使用示例 授权模式: 环境准备 a)调整项目结构如下: b)调整cz.Id ...
- Spring Security OAuth2 微服务认证中心自定义授权模式扩展以及常见登录认证场景下的应用实战
一. 前言 [APP 移动端]Spring Security OAuth2 手机短信验证码模式 [微信小程序]Spring Security OAuth2 微信授权模式 [管理系统]Spring Se ...
- IdentityServer4 实现自定义 GrantType 授权模式
OAuth 2.0 默认四种授权模式(GrantType): 授权码模式(authorization_code) 简化模式(implicit) 密码模式(password) 客户端模式(client_ ...
- 【.NET Core项目实战-统一认证平台】第十四章 授权篇-自定义授权方式
[.NET Core项目实战-统一认证平台]开篇及目录索引 上篇文章我介绍了如何强制令牌过期的实现,相信大家对IdentityServer4的验证流程有了更深的了解,本篇我将介绍如何使用自定义的授权方 ...
- 一看就懂的IdentityServer4认证授权设计方案
查阅了大多数相关资料,总结设计一个IdentityServer4认证授权方案,我们先看理论,后设计方案. 1.快速理解认证授权 我们先看一下网站发起QQ认证授权,授权通过后获取用户头像,昵称的流程. ...
- IdentityServer4 (1) 客户端授权模式(Client Credentials)
写在前面 1.源码(.Net Core 2.2) git地址:https://github.com/yizhaoxian/CoreIdentityServer4Demo.git 2.相关章节 2.1. ...
随机推荐
- JVM内存结构、参数调优和内存泄露分析
1. JVM内存区域和参数配置 1.1 JVM内存结构 Java堆(Heap) Java堆是被所有线程共享的一块内存区域,在虚拟机启动时创建.此内存区域的唯一目的就是存放对象实例,几乎所有的对象实例都 ...
- SpringBoot2.1.9+dubbo2.7.3+Nacos1.1.4构建你的微服务体系
简单几步使用最新版本的DUBBO构建你的微服务体系 NACOS注册中心 从github下载最新版本的nacos 上传至服务器并解压 单机启动sh startup.sh -m standalone na ...
- 20190723_C中的调用可变函数
今天联系了 C 中调用可变参函数 参考网站:https://www.runoob.com/cprogramming/c-standard-library-stdarg-h.html 代码1: 向被调用 ...
- C++学习笔记11_STL
STL又叫标准模板库,提供各种容器. STL是C++一部分,不休要额外安装什么,它被内建在编译器之内. STL重要特点是,数据结构和实现分离. *所谓迭代器,类似一个游标,使用++指向下一个元素,使用 ...
- 学习笔记41_Spring.Net
Spring.Net:由容器负责创建对象,容器读取配置文件来初始化对象,配置文件须符合 Spring.Net范式: 准备材料: Common.Loggin.dll,Spring.Core.dll 第一 ...
- Python基本数据结构之文件操作
用word操作一个文件的流程如下: 1.找到文件,双击打开 2.读或修改 3.保存&关闭 用python操作文件也差不多: f=open(filename) # 打开文件 f.write(&q ...
- insmod: can't insert 'btn_drv.ko': Operation not permitted
检测内核是否以及支持 要插入的驱动,若内核支持,则需要裁减掉内核支持的驱动才能安装上自己所写的驱动程序.
- TensorFlow2.0(10):加载自定义图片数据集到Dataset
.caret, .dropup > .btn > .caret { border-top-color: #000 !important; } .label { border: 1px so ...
- 在VMware环境下安装Windows2008
1.软硬件安装 软件:推荐使用VMware,这里我使用的是VMware15 镜像:Windows 2008 如果没有镜像可以到这里 链接:https://pan.baidu.com/s/1r_7K-U ...
- on duplicate key update 的使用(数据库有就修改,没有就添加数据)
on duplicate key update 使用:当数据库中有该数据就修改,没有就添加 MySQL语句如下: # id 不存在则添加数据,id存在就更新数据 INSERT INTO t_user( ...