背景

一直对OAuth 2.0的四种授权模式比较好奇,了解的仅限网上的资料,没有使用代码体验过,这次使用spring-security-oauth2来体验这四种模式的整个过程。

相关代码

  1. pom文件
  2. <dependencies>
  3. <dependency>
  4. <groupId>org.springframework.boot</groupId>
  5. <artifactId>spring-boot-starter-security</artifactId>
  6. <version>2.1.4.RELEASE</version>
  7. </dependency>
  8. <dependency>
  9. <groupId>org.springframework.boot</groupId>
  10. <artifactId>spring-boot-starter-web</artifactId>
  11. <version>2.1.4.RELEASE</version>
  12. </dependency>
  13. <dependency>
  14. <groupId>org.springframework.security.oauth</groupId>
  15. <artifactId>spring-security-oauth2</artifactId>
  16. <version>2.0.16.RELEASE</version>
  17. <exclusions>
  18. <exclusion>
  19. <artifactId>spring-core</artifactId>
  20. <groupId>org.springframework</groupId>
  21. </exclusion>
  22. <exclusion>
  23. <artifactId>spring-context</artifactId>
  24. <groupId>org.springframework</groupId>
  25. </exclusion>
  26. <exclusion>
  27. <artifactId>spring-beans</artifactId>
  28. <groupId>org.springframework</groupId>
  29. </exclusion>
  30. <exclusion>
  31. <artifactId>spring-security-core</artifactId>
  32. <groupId>org.springframework.security</groupId>
  33. </exclusion>
  34. </exclusions>
  35. </dependency>
  36. <dependency>
  37. <groupId>com.google.guava</groupId>
  38. <artifactId>guava</artifactId>
  39. <version>26.0-jre</version>
  40. </dependency>
  41. </dependencies>
  1. 配置类
  2. @Configuration
  3. @EnableAuthorizationServer
  4. public class MyAuthorizationServerConfigurerAdapter extends AuthorizationServerConfigurerAdapter {
  5. @Override
  6. public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
  7. clients
  8. .inMemory()
  9. .withClient("clientUser")
  10. .secret("{bcrypt}" + new BCryptPasswordEncoder().encode("123456"))
  11. .authorizedGrantTypes("authorization_code", "implicit", "password", "client_credentials");
  12. }
  13. @Override
  14. public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
  15. DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
  16. UserDetails userDetails = User.withUsername("username")
  17. .password("{bcrypt}" + new BCryptPasswordEncoder().encode("password"))
  18. .roles("123")
  19. .build();
  20. InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager(userDetails);
  21. daoAuthenticationProvider.setUserDetailsService(inMemoryUserDetailsManager);
  22. AuthenticationManager authenticationManager = new ProviderManager(
  23. Lists.<AuthenticationProvider>newArrayList(daoAuthenticationProvider));
  24. endpoints.authenticationManager(authenticationManager);
  25. }
  26. }
  27. @Configuration
  28. @EnableWebSecurity
  29. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  30. @Override
  31. protected void configure(HttpSecurity http) throws Exception {
  32. http.httpBasic();
  33. }
  34. @Bean
  35. public InMemoryUserDetailsManager inMemoryUserDetailsManager(
  36. SecurityProperties properties) {
  37. SecurityProperties.User user = properties.getUser();
  38. List<String> roles = user.getRoles();
  39. return new InMemoryUserDetailsManager(User.withUsername("user")
  40. .password("{bcrypt}" + new BCryptPasswordEncoder().encode("123456"))
  41. .roles(StringUtils.toStringArray(roles)).build());
  42. }
  43. }
  1. 启动类
  2. @SpringBootApplication(
  3. exclude = UserDetailsServiceAutoConfiguration.class
  4. // excludeName = "org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration"
  5. )
  6. public class SpringSecurityStudyApplication {
  7. public static void main(String[] args) {
  8. SpringApplication.run(SpringSecurityStudyApplication.class, args);
  9. }
  10. }

授权码模式

第一步 访问GET /oauth/authorize

相关代码在org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint

org.springframework.security.oauth2.provider.endpoint.WhitelabelApprovalEndpoint

请求参数和返回结果如下:

返回结果在浏览器上展示的话,是让用户来勾选是否同意授权的一个页面,还有返回结果的_csrf的值要作为第二步的参数。

curl如下:

  1. curl --location --request GET 'http://127.0.0.1:8090/oauth/authorize?response_type=code&client_id=clientUser&redirect_uri=https://www.baidu.com/&scope=scope' \
  2. --header 'Authorization: Basic dXNlcjoxMjM0NTY=' \
  3. --header 'Cookie: JSESSIONID=AB254815273DB81F1F3BAF74E94DAAB6'

第二步 访问POST /oauth/authorize

相关代码在org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint

crul如下:

  1. curl --location --request POST 'http://127.0.0.1:8090/oauth/authorize?user_oauth_approval=true&scope.scope=true&_csrf=a95516db-6ce2-4033-9b81-1060b6c4d829' \
  2. --header 'Cookie: JSESSIONID=73E846796ACB7818E09B93AC4CFD320D'

_csrf 要使用第一步返回的结果,在返回头的Location里可以得到授权码

第一个参数必须要有,因为:

  1. <input name="user_oauth_approval" value="true" type="hidden"/>
  2. @RequestMapping(value = "/oauth/authorize", method = RequestMethod.POST, params = OAuth2Utils.USER_OAUTH_APPROVAL)
  3. public View approveOrDeny(@RequestParam Map<String, String> approvalParameters, Map<String, ?> model, SessionStatus sessionStatus, Principal principal) {
  4. }
  5. public static final String USER_OAUTH_APPROVAL = "user_oauth_approval";

第二个参数是用户是否同意授权

第三步 访问POST /oauth/token

相关代码在org.springframework.security.oauth2.provider.endpoint.TokenEndpoint

code 使用第二步的返回结果

crul如下:

  1. curl --location --request POST 'http://127.0.0.1:8090/oauth/token' \
  2. --header 'Authorization: Basic Y2xpZW50VXNlcjoxMjM0NTY=' \
  3. --header 'Content-Type: application/x-www-form-urlencoded' \
  4. --header 'Cookie: JSESSIONID=5D41BF01BC875BDF266D3C2178537F21' \
  5. --data-urlencode 'grant_type=authorization_code' \
  6. --data-urlencode 'code=1pakV1' \
  7. --data-urlencode 'redirect_uri=https://www.baidu.com/' \
  8. --data-urlencode 'client_id=clientUser' \
  9. --data-urlencode 'scope=scope'

简化模式

第一步 访问GET /oauth/authorize

crul如下:

  1. curl --location --request GET 'http://127.0.0.1:8090/oauth/authorize?response_type=token&client_id=clientUser&redirect_uri=https://www.baidu.com/&scope=scope' \
  2. --header 'Authorization: Basic dXNlcjoxMjM0NTY=' \
  3. --header 'Cookie: JSESSIONID=6AD429F6CF30C10C0E9F1A35EC78A790'

第二步 访问POST /oauth/authorize



crul如下:

  1. curl --location --request POST 'http://127.0.0.1:8090/oauth/authorize?user_oauth_approval=true&scope.scope=true&_csrf=1ba6be5e-845f-47f2-9680-db613adc47c7' \
  2. --header 'Cookie: JSESSIONID=6AD429F6CF30C10C0E9F1A35EC78A790'

密码模式

直接 访问POST /oauth/token

curl如下:

  1. curl --location --request POST 'http://127.0.0.1:8090/oauth/token' \
  2. --header 'Authorization: Basic Y2xpZW50VXNlcjoxMjM0NTY=' \
  3. --header 'Content-Type: application/x-www-form-urlencoded' \
  4. --header 'Cookie: JSESSIONID=7E149951AB7D3C03E31E21450754DAAE' \
  5. --data-urlencode 'grant_type=password' \
  6. --data-urlencode 'username=username' \
  7. --data-urlencode 'scope=scope' \
  8. --data-urlencode 'password=password'

客户端模式

直接 访问POST /oauth/token

curl如下:

  1. curl --location --request POST 'http://127.0.0.1:8090/oauth/token' \
  2. --header 'Authorization: Basic Y2xpZW50VXNlcjoxMjM0NTY=' \
  3. --header 'Content-Type: application/x-www-form-urlencoded' \
  4. --header 'Cookie: JSESSIONID=7E149951AB7D3C03E31E21450754DAAE' \
  5. --data-urlencode 'grant_type=client_credentials' \
  6. --data-urlencode 'scope=scope'

参考

理解OAuth 2.0 - 阮一峰

使用 spring-security-oauth2 体验 OAuth 2.0 的四种授权模式的更多相关文章

  1. OAuth 2.0 的四种授权模式

    RFC 6749 OAuth 2.0 的标准是 RFC 6749 文件.该文件先解释了 OAuth 是什么. OAuth 引入了一个授权层,用来分离两种不同的角色:客户端和资源所有者.......资源 ...

  2. OAuth2.0的四种授权模式

    1.什么是OAuth2 OAuth(开放授权)是一个开放标准,允许用户授权第三方移动应用访问他们存储在另外的服务提供者上的信息,而不需要将用户名和密码提供给第三方移动应用或分享他们数据的所有内容,OA ...

  3. OAuth2.0的四种授权模式(转)

    1. OAuth2简易实战(一)-四种模式 1.1. 隐式授权模式(Implicit Grant) 第一步:用户访问页面时,重定向到认证服务器. 第二步:认证服务器给用户一个认证页面,等待用户授权. ...

  4. OAuth 2.0 的四种方式

    上一篇文章介绍了 OAuth 2.0 是一种授权机制,主要用来颁发令牌(token).本文接着介绍颁发令牌的实务操作. 下面我假定,你已经理解了 OAuth 2.0 的含义和设计思想,否则请先阅读这个 ...

  5. OAuth2.0 四种授权模式

    OAuth2.0简单笔记(四种授权模式) 金天:坚持写东西,不是一件容易的事,换句话说其实坚持本身都不是一件容易的事.如果学习有捷径,那就是不断实践,不断积累.写笔记,其实是给自己看的,是体现积累的一 ...

  6. OAuth2.0学习(2-1)Spring Security OAuth2.0 开发指南

    开发指南:http://www.cnblogs.com/xingxueliao/p/5911292.html Spring OAuth2.0 提供者实现原理: Spring OAuth2.0提供者实际 ...

  7. Spring Security OAuth2.0认证授权一:框架搭建和认证测试

    一.OAuth2.0介绍 OAuth(开放授权)是一个开放标准,允许用户授权第三方应用访问他们存储在另外的服务提供者上的信息,而不 需要将用户名和密码提供给第三方应用或分享他们数据的所有内容. 1.s ...

  8. Spring Security OAuth2 开发指南

    官方原文:http://projects.spring.io/spring-security-oauth/docs/oauth2.html 翻译及修改补充:Alex Liao. 转载请注明来源:htt ...

  9. Spring Security OAuth2 开发指南(非最新版本)

    请注意哈,本文翻译的时候,官网的的版本和本文翻译的时候是一一对应的. 但是官网已经更新文档和概念了,因此和本文翻译的就不在是同一个范围了. 因此我已经将标题修改为(非最新版本),各位老铁直接看官网就可 ...

随机推荐

  1. 『现学现忘』Git对象 — 15、blob对象介绍

    目录 (一)Git对象的存放目录 (二)Git中对象类型 (三)blob对象 1.blob对象说明 (1)blob对象定义 (2)blob对象说明 (3)blob对象存储的方式 (4)查看blob对象 ...

  2. python数据可视化-matplotlib入门(5)-饼图和堆叠图

    饼图常用于统计学模块,画饼图用到的方法为:pie( ) 一.pie()函数用来绘制饼图 pie(x, explode=None, labels=None, colors=None, autopct=N ...

  3. 撸了一个 Feign 增强包 V2.0 升级版

    前言 大概在两年前我写过一篇 撸了一个 Feign 增强包,当时准备是利用 SpringBoot + K8s 构建应用,这个库可以类似于 SpringCloud 那样结合 SpringBoot 使用声 ...

  4. 聊聊 HTTPS

    聊聊 HTTPS 本文写于 2021 年 6 月 30 日 最近工作也是越来越忙了,不像上学的时候,一天下来闲着没事可以写两篇博客. 今天来聊一下 HTTPS. HTTP HTTP 是不安全的协议. ...

  5. mysql忘记root密码实现免密登录

    1.配置my.cnf文件,跳过授权表: skip-grant-tables 2.重启mysqld服务 3.z直接mysql登录 4.use mysql这个数据库 5.设置密码: update user ...

  6. 2020级cpp机考模拟题A卷-#题解2

    这部分的题目都有一定难度,有兴趣的同学可以钻研一下. 特此感谢来自BDT20030  tql的支持. 2:素数的和-2 题意: 计算不大于m的素数之和.(多么容易理解的题目啊,对吧) 题解(有点复杂的 ...

  7. 【单片机】CH32V103v8t6 - PA5-外部中断测试程序

    main.c文件内容 /* *@Note 外部中断线例程: EXTI_Line5(PA5) PA5设置上拉输入,下降沿触发中断. */ #include "debug.h" /** ...

  8. linux 查询文件命令

    jps; 当前服务器中所有的java进程: jps |grep XXX; 查询当前服务器某个进程: locate xxx;查询某个文件的位置:

  9. 开源的.Net 工作流引擎Elsa初试——创建工作流服务器和图形化工作流配置管理应用

    微软的Workflow Foundation基于.Net Framework,并且没有向.Net Core迁移的计划.我们的很多项目使用了工作流引擎,这些项目向.Net Core以及更高版本迁移时遇到 ...

  10. python基础学习6

    Python的基础学习6 内容概要 while + else 死循环.while的嵌套 for循环基本使用 range关键字 for循环补充.爬虫 基本数据类型及内置方法 内容详情 while + e ...