IdentityServer4 实现 OAuth 2.0(密码模式 - HTTP Post 方式)
之前写了一篇文章:《IdentityServer4 实现 OpenID Connect 和 OAuth 2.0》
上面这篇文章虽然详细,但都是点到为止的介绍,并没有实际应用的示例,所以,后面在真正去实现的时候,踩到了自己之前种下的很多坑。
业务场景:前后端分离项目,前端调用后端业务服务需要授权访问(提供access_token
),access_token
在用户登录的时候(用户名和密码登录),由授权中心生成access_token
并返回给前端,这样前端就可以拿到access_token
,去调用后端业务服务了。
一开始,我使用的GrantTypes.Implicit
模式,登录页面在授权中心,登录成功之后会跳到callback.htm#access_token=*
页面,前端调用使用oidc-client
组件,然后获取access_token
,当时使用还没什么,现在觉得真是一团乱麻,前后端分离的项目,在授权中心居然把登录页面放在服务中了,但我后面还是没有意识到GrantTypes.Implicit
的问题,而是尝试在这种模式下,写HTTP Post
请求授权中心(提供用户名和密码),然后没然后,一团糟。。。
使用 IdentityServer4 实现上面的业务场景,其实很简单,只要使用GrantTypes.GrantTypes.ResourceOwnerPassword
模式,就可以了。
Startup.ConfigureServices
配置代码:
var builder = services.AddIdentityServer();
builder.AddTemporarySigningCredential()//.AddInMemoryIdentityResources(Config.GetIdentityResources()).AddInMemoryApiResources(Config.GetApiResources()).AddInMemoryClients(new List<Client>{new Client{ClientId = "client_id_1",AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,AllowOfflineAccess = true,AccessTokenLifetime = 3600 * 6, //6小时SlidingRefreshTokenLifetime = 1296000, //15天ClientSecrets ={new Secret("secret".Sha256())},AllowedScopes ={IdentityServerConstants.StandardScopes.OfflineAccess, "api1"}}});
builder.AddResourceOwnerValidator<ResourceOwnerPasswordValidator>();
ResourceOwnerPasswordValidator
示例代码:
public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
{private readonly IUserService _userService;public ResourceOwnerPasswordValidator(IUserService userService){_userService = userService;}public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context){var userId = await _userService.Login(context.UserName, context.Password);if (userId != 0){context.Result = new GrantValidationResult(userId.ToString(), OidcConstants.AuthenticationMethods.Password);}}
}
使用ResourceOwnerPasswordValidator
的作用,就是自定义用户登录的用户名密码判断,而不是使用 IdentityServer4 的TestUser
。
请求示例:IdentityServer4 Token Endpoint
获取access_token
请求示例:
刷新access_token
请求示例:
也可以服务端进行请求,示例代码:
private async Task<TokenResponse> GetToken(string clientId, string clientSecret, string grantType, string userName, string password, string scope)
{var client = new DiscoveryClient($"http://localhost:5001");client.Policy.RequireHttps = false;var disco = await client.GetAsync();var tokenClient = new TokenClient(disco.TokenEndpoint, clientId, clientSecret);return await tokenClient.RequestResourceOwnerPasswordAsync(userName, password, scope);
}private async Task<TokenResponse> GetRefreshToken(string clientId, string clientSecret, string grantType, string refreshToken)
{var client = new DiscoveryClient($"http://localhost:5001");client.Policy.RequireHttps = false;var disco = await client.GetAsync();var tokenClient = new TokenClient(disco.TokenEndpoint, clientId, clientSecret);return await tokenClient.RequestRefreshTokenAsync(refreshToken);
}
参考资料:
- ASP.NET CORE IDENTITYSERVER4 RESOURCE OWNER PASSWORD FLOW WITH CUSTOM USERREPOSITORY
- IResourceOwnerPasswordValidator isn't being called?
- Client scope definition with IResourceOwnerPasswordValidator
- Resource Owner Password Validation
- IdentityServer4 .netCore RefreshToken Example
- IdentityServer4 Refresh Tokens
- IdentityServer4 Client
- IdentityServer4 Discovery Endpoint
IdentityServer4 实现 OAuth 2.0(密码模式 - HTTP Post 方式)相关推荐
- 简单谈谈OAuth 2.0的四种认证方式
简单谈谈OAuth 2.0的四种认证方式 一.基本认识 1.1 OAuth认证中的四种角色 二.认证方式 2.1 授权码认证 2.2 简化认证 2.3 密码认证 2.4 客户端认证 一.基本认识 在小 ...
- Security-OAuth2.0 密码模式之客户端实现
我的OAuth2.0 客户端项目目录 pom 的配置 <?xml version="1.0" encoding="UTF-8"?> <proj ...
- 实战讲解Spring Oauth2.0密码模式和授权码模式(内存inMemory+持久化jdbc配置)
1 缘起 先吐槽, 在搜索关于Oauth2.0授权码方式认证时, 遇到的问题比较多,一句话,按照其分享的步骤一步一步来,最终,无法成功, 本想,抄近路,看一些前人分享的应用案例,直接使用, 近路不通, ...
- OAuth 2.0授权模式时序图
目录 Authorization Code Flow Authorization Code Flow With PKCE Client Credentials Flow Resource Owner ...
- 可能是第二好的 Spring OAuth 2.0 文章,艿艿端午在家写了 3 天~
" 本文在提供完整代码示例,可见 https://github.com/YunaiV/SpringBoot-Labs 的 lab-68-spring-security-oauth 目录. 原 ...
- OAuth 2.0 教程
OAuth 2.0 (原文:http://tutorials.jenkov.com/oauth2/index.html) demo: https://github.com/qihaiyan/ng-bo ...
- OAuth 2.0实战(一)-通俗光速入门
1 什么是开放平台(Open Platform) 在软件行业和网络中,开放平台指软件系统通过公开其API使外部程序可增加该软件系统的功能或使用该软件系统的资源,而无需更改该软件系统的源码. 在互联网时 ...
- OAuth 2.0 笔记 (1) 世界观
OAuth 2.0笔记(1)世界观 来自台湾同胞的博客:https://blog.yorkxin.org/posts/oauth2-1-introduction.html,繁体字做了复制转换. 最近需 ...
- oauth password模式_SpringBoot OAuth2.0 认证授权(密码模式)
SpringBoot 整合 SpringSecurity,token 落地,前后端分离接口安全. SpringBoot 环境搭建和入门:Spring Boot 2.x 快速入门 导入 mysql 脚本 ...
最新文章
- adb devices只显示List of devices attached
- 讲真,下次打死我也不敢随便改serialVersionUID了
- python语言能干什么-学Python语言可以做什么?
- 远程调用RestTemplate
- 区块链技术 好文收藏
- c++矩阵作为函数输入变量_C++实现矩阵乘法
- 高德在提升定位精度方面的探索和实践
- linux下mknod命令介绍
- C++栈与队列基本操作
- C语言课程设计 简单的单词学习系统
- Ubuntu18.04 安装NVIDIA英伟达驱动教程
- 人民大学 环境学院 雷洋(1987-2016)
- 常见的数字高程模型结构有哪些?
- 基金使用计划 数学建模 matlab,01B基金使用计划(数学建模).ppt
- 经验整理-win10安装ubuntu18.04.2双系统(NVIDIA Geforce GTX 1060独显)
- pvid与access的关系_关于Trunk、Hybrid、Access、Tag、Untag、Pvid的关系与区别
- 计算机应用中的pe是什么意思,重装系统的pe是指什么?pe有什么作用?
- AutoCAD2014打开一闪而过解决方法
- 建行的项目外包中的一些经历
- Android中四大组件