之前写了一篇文章:《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 方式)相关推荐

  1. 简单谈谈OAuth 2.0的四种认证方式

    简单谈谈OAuth 2.0的四种认证方式 一.基本认识 1.1 OAuth认证中的四种角色 二.认证方式 2.1 授权码认证 2.2 简化认证 2.3 密码认证 2.4 客户端认证 一.基本认识 在小 ...

  2. Security-OAuth2.0 密码模式之客户端实现

    我的OAuth2.0 客户端项目目录 pom 的配置 <?xml version="1.0" encoding="UTF-8"?> <proj ...

  3. 实战讲解Spring Oauth2.0密码模式和授权码模式(内存inMemory+持久化jdbc配置)

    1 缘起 先吐槽, 在搜索关于Oauth2.0授权码方式认证时, 遇到的问题比较多,一句话,按照其分享的步骤一步一步来,最终,无法成功, 本想,抄近路,看一些前人分享的应用案例,直接使用, 近路不通, ...

  4. OAuth 2.0授权模式时序图

    目录 Authorization Code Flow Authorization Code Flow With PKCE Client Credentials Flow Resource Owner ...

  5. 可能是第二好的 Spring OAuth 2.0 文章,艿艿端午在家写了 3 天~

    " 本文在提供完整代码示例,可见 https://github.com/YunaiV/SpringBoot-Labs 的 lab-68-spring-security-oauth 目录. 原 ...

  6. OAuth 2.0 教程

    OAuth 2.0 (原文:http://tutorials.jenkov.com/oauth2/index.html) demo: https://github.com/qihaiyan/ng-bo ...

  7. OAuth 2.0实战(一)-通俗光速入门

    1 什么是开放平台(Open Platform) 在软件行业和网络中,开放平台指软件系统通过公开其API使外部程序可增加该软件系统的功能或使用该软件系统的资源,而无需更改该软件系统的源码. 在互联网时 ...

  8. OAuth 2.0 笔记 (1) 世界观

    OAuth 2.0笔记(1)世界观 来自台湾同胞的博客:https://blog.yorkxin.org/posts/oauth2-1-introduction.html,繁体字做了复制转换. 最近需 ...

  9. oauth password模式_SpringBoot OAuth2.0 认证授权(密码模式)

    SpringBoot 整合 SpringSecurity,token 落地,前后端分离接口安全. SpringBoot 环境搭建和入门:Spring Boot 2.x 快速入门 导入 mysql 脚本 ...

最新文章

  1. adb devices只显示List of devices attached
  2. 讲真,下次打死我也不敢随便改serialVersionUID了
  3. python语言能干什么-学Python语言可以做什么?
  4. 远程调用RestTemplate
  5. 区块链技术 好文收藏
  6. c++矩阵作为函数输入变量_C++实现矩阵乘法
  7. 高德在提升定位精度方面的探索和实践
  8. linux下mknod命令介绍
  9. C++栈与队列基本操作
  10. C语言课程设计 简单的单词学习系统
  11. Ubuntu18.04 安装NVIDIA英伟达驱动教程
  12. 人民大学 环境学院 雷洋(1987-2016)
  13. 常见的数字高程模型结构有哪些?
  14. 基金使用计划 数学建模 matlab,01B基金使用计划(数学建模).ppt
  15. 经验整理-win10安装ubuntu18.04.2双系统(NVIDIA Geforce GTX 1060独显)
  16. pvid与access的关系_关于Trunk、Hybrid、Access、Tag、Untag、Pvid的关系与区别
  17. 计算机应用中的pe是什么意思,重装系统的pe是指什么?pe有什么作用?
  18. AutoCAD2014打开一闪而过解决方法
  19. 建行的项目外包中的一些经历
  20. Android中四大组件

热门文章

  1. spring 全局变量_精华:关于Spring的15点总结
  2. shell脚本——系统变量 与 变量(定义 使用 只读 删除)
  3. 最常用git命令汇总(参考列表)
  4. Android-实现切换Fragment页功能
  5. 集合2--毕向东java基础教程视频学习笔记
  6. Oracle归档已满的处理办法
  7. 经常下载的朋友注意了,教你怎样硬盘零伤害(从论坛上拷下来收藏的)
  8. wpf学习笔记---初识xaml标签语言
  9. 2016各大公司校招薪水曝光:年薪28万,这只是零花钱
  10. 聚焦CSDN技术主题月:深度学习框架的重构与思考专场回顾