文章目录

  • Spring Cloud入门系列汇总
  • 摘要
  • 单点登录简介
  • 创建oauth2-client模块
  • 修改授权服务器配置
  • 网页单点登录演示
  • 调用接口单点登录演示
  • oauth2-client添加权限校验
  • 使用到的模块
  • 项目源码地址

项目使用的Spring Cloud为Hoxton版本,Spring Boot为2.2.2.RELEASE版本

Spring Cloud入门系列汇总

序号 内容 链接地址
1 Spring Cloud入门-十分钟了解Spring Cloud https://blog.csdn.net/ThinkWon/article/details/103715146
2 Spring Cloud入门-Eureka服务注册与发现(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103726655
3 Spring Cloud入门-Ribbon服务消费者(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103729080
4 Spring Cloud入门-Hystrix断路器(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103732497
5 Spring Cloud入门-Hystrix Dashboard与Turbine断路器监控(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103734664
6 Spring Cloud入门-OpenFeign服务消费者(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103735751
7 Spring Cloud入门-Zuul服务网关(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103738851
8 Spring Cloud入门-Config分布式配置中心(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103739628
9 Spring Cloud入门-Bus消息总线(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103753372
10 Spring Cloud入门-Sleuth服务链路跟踪(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103753896
11 Spring Cloud入门-Consul服务注册发现与配置中心(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103756139
12 Spring Cloud入门-Gateway服务网关(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103757927
13 Spring Cloud入门-Admin服务监控中心(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103758697
14 Spring Cloud入门-Oauth2授权的使用(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103761687
15 Spring Cloud入门-Oauth2授权之JWT集成(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103763364
16 Spring Cloud入门-Oauth2授权之基于JWT完成单点登录(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103766368
17 Spring Cloud入门-Nacos实现注册和配置中心(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103769680
18 Spring Cloud入门-Sentinel实现服务限流、熔断与降级(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103770879
19 Spring Cloud入门-Seata处理分布式事务问题(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103786102
20 Spring Cloud入门-汇总篇(Hoxton版本) https://blog.csdn.net/ThinkWon/article/details/103786588

摘要

Spring Cloud Security 为构建安全的SpringBoot应用提供了一系列解决方案,结合Oauth2可以实现单点登录功能,本文将对其单点登录用法进行详细介绍。

单点登录简介

单点登录(Single Sign On)指的是当有多个系统需要登录时,用户只需登录一个系统,就可以访问其他需要登录的系统而无需登录。

创建oauth2-client模块

这里我们创建一个oauth2-client服务作为需要登录的客户端服务,使用上一节中的oauth2-jwt-server服务作为授权服务,当我们在oauth2-jwt-server服务上登录以后,就可以直接访问oauth2-client需要登录的接口,来演示下单点登录功能。

在pom.xml中添加相关依赖:

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-security</artifactId>
</dependency>

在application.yml中进行配置:

server:port: 9501servlet:session:cookie:# 防止cookie冲突,冲突会导致登录验证不通过name: OAUTH2-CLIENT-SESSIONIDoauth2-service-url: http://localhost:9401spring:application:name: oauth2-clientsecurity:# 与oauth2-server对应的配置oauth2:client:client-id: adminclient-secret: admin123456user-authorization-uri: ${oauth2-service-url}/oauth/authorizeaccess-token-uri: ${oauth2-service-url}/oauth/tokenresource:jwt:key-uri: ${oauth2-service-url}/oauth/token_key

在启动类上添加@EnableOAuth2Sso注解来启用单点登录功能:

@EnableOAuth2Sso
@SpringBootApplication
public class Oauth2ClientApplication {public static void main(String[] args) {SpringApplication.run(Oauth2ClientApplication.class, args);}}

添加接口用于获取当前登录用户信息:

@RestController
@RequestMapping("/user")
public class UserController {@GetMapping("/getCurrentUser")public Object getCurrentUser(Authentication authentication) {return authentication;}}

修改授权服务器配置

修改oauth2-jwt-server模块中的AuthorizationServerConfig类,将绑定的跳转路径为http://localhost:9501/login,并添加获取秘钥时的身份认证。

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {//以上省略一堆代码...@Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {clients.inMemory()// 配置client_id.withClient("admin")// 配置client_secret.secret(passwordEncoder.encode("admin123456"))// 配置访问token的有效期.accessTokenValiditySeconds(3600)// 配置刷新token的有效期.refreshTokenValiditySeconds(864000)// 配置redirect_uri,用于授权成功后的跳转// .redirectUris("http://www.baidu.com")// 单点登录时配置.redirectUris("http://localhost:9501/login")// 自动授权配置// .autoApprove(true)// 配置申请的权限范围.scopes("all")// 配置grant_type,表示授权类型.authorizedGrantTypes("authorization_code", "password", "refresh_token");}@Overridepublic void configure(AuthorizationServerSecurityConfigurer security) throws Exception {// 获取密钥需要身份认证,使用单点登录时必须配置security.tokenKeyAccess("isAuthenticated()");}
}

网页单点登录演示

启动oauth2-client服务和oauth2-jwt-server服务;

访问客户端需要授权的接口http://localhost:9501/user/getCurrentUser会跳转到授权服务的登录界面;

进行登录操作后跳转到授权页面;

授权后会跳转到原来需要权限的接口地址,展示登录用户信息;

如果需要跳过授权操作进行自动授权可以添加autoApprove(true)配置:

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {//以上省略一堆代码...@Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {clients.inMemory()// 配置client_id.withClient("admin")// 配置client_secret.secret(passwordEncoder.encode("admin123456"))// 配置访问token的有效期.accessTokenValiditySeconds(3600)// 配置刷新token的有效期.refreshTokenValiditySeconds(864000)// 配置redirect_uri,用于授权成功后的跳转// .redirectUris("http://www.baidu.com")// 单点登录时配置.redirectUris("http://localhost:9501/login")// 自动授权配置.autoApprove(true)// 配置申请的权限范围.scopes("all")// 配置grant_type,表示授权类型.authorizedGrantTypes("authorization_code", "password", "refresh_token");}
}

调用接口单点登录演示

这里我们使用Postman来演示下如何使用正确的方式调用需要登录的客户端接口。

访问客户端需要登录的接口:http://localhost:9501/user/getCurrentUser

使用Oauth2认证方式获取访问令牌:

输入获取访问令牌的相关信息,点击请求令牌:

此时会跳转到授权服务器进行登录操作:

登录成功后使用获取到的令牌:

最后请求接口可以获取到如下信息:

{"authorities": [{"authority": "admin"}],"details": {"remoteAddress": "0:0:0:0:0:0:0:1","sessionId": "6F5A553BB678C7272145FF9FF2A5D8F4","tokenValue": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJqb3Vyd29uIiwic2NvcGUiOlsiYWxsIl0sImV4cCI6MTU3NzY4OTc2NiwiYXV0aG9yaXRpZXMiOlsiYWRtaW4iXSwianRpIjoiZjAwYjVkMGUtNjFkYi00YjBmLTkyNTMtOWQxZDYwOWM4ZWZmIiwiY2xpZW50X2lkIjoiYWRtaW4iLCJlbmhhbmNlIjoiZW5oYW5jZSBpbmZvIn0.zdgFTWJt3DnAsjpQRU6rNA_iM7gVHX7E9bCyF73MOSM","tokenType": "bearer","decodedDetails": null},"authenticated": true,"userAuthentication": {"authorities": [{"authority": "admin"}],"details": null,"authenticated": true,"principal": "jourwon","credentials": "N/A","name": "jourwon"},"clientOnly": false,"oauth2Request": {"clientId": "admin","scope": ["all"],"requestParameters": {"client_id": "admin"},"resourceIds": [],"authorities": [],"approved": true,"refresh": false,"redirectUri": null,"responseTypes": [],"extensions": {},"grantType": null,"refreshTokenRequest": null},"principal": "jourwon","credentials": "","name": "jourwon"
}

oauth2-client添加权限校验

添加配置开启基于方法的权限校验:

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(101)
public class SecurityConfig extends WebSecurityConfigurerAdapter {}

在UserController中添加需要admin权限的接口:

@RestController
@RequestMapping("/user")
public class UserController {@PreAuthorize("hasAuthority('admin')")@GetMapping("/auth/admin")public Object adminAuth() {return "Has admin auth!";}}

访问需要admin权限的接口:http://localhost:9501/user/auth/admin

使用没有admin权限的帐号,比如andy:123456获取令牌后访问该接口,会发现没有权限访问。

使用到的模块

springcloud-learning
├── oauth2-jwt-server -- 使用jwt的oauth2认证测试服务
└── oauth2-client -- 单点登录的oauth2客户端服务

项目源码地址

GitHub项目源码地址

Spring Cloud入门-Oauth2授权之基于JWT完成单点登录(Hoxton版本)相关推荐

  1. spring cloud 入门系列七:基于Git存储的分布式配置中心--Spring Cloud Config

    我们前面接触到的spring cloud组件都是基于Netflix的组件进行实现的,这次我们来看下spring cloud 团队自己创建的一个全新项目:Spring Cloud Config. 它用来 ...

  2. 基于JWT实现单点登录

    单点登录概述: 多系统共存下,用户在一处地方登录,得到其他所有系统的信任,无需再次登录. 自己的理解:在前端用户点击登录触发后端登录接口,登录成功的时候,后端jwt生成一个token,后端将token ...

  3. Spring Cloud入门-Admin服务监控中心(Hoxton版本)

    文章目录 Spring Cloud入门系列汇总 摘要 Spring Boot Admin 简介 创建admin-server模块 创建admin-client模块 监控信息演示 结合注册中心使用 修改 ...

  4. Spring Cloud入门-Sentinel实现服务限流、熔断与降级(Hoxton版本)

    文章目录 Spring Cloud入门系列汇总 摘要 Sentinel简介 安装Sentinel控制台 创建sentinel-service模块 限流功能 创建RateLimitController类 ...

  5. Spring Cloud入门-Ribbon服务消费者(Hoxton版本)

    文章目录 Spring Cloud入门系列汇总 摘要 Ribbon简介 RestTemplate的使用 GET请求方法 getForObject方法 getForEntity方法 POST请求方法 p ...

  6. Spring Cloud入门-Nacos实现注册和配置中心(Hoxton版本)

    文章目录 Spring Cloud入门系列汇总 摘要 Nacos简介 使用Nacos作为注册中心 安装并运行Nacos 创建应用注册到Nacos 负载均衡功能 使用Nacos作为配置中心 创建naco ...

  7. Spring Cloud入门-Gateway服务网关(Hoxton版本)

    文章目录 Spring Cloud入门系列汇总 摘要 Gateway 简介 相关概念 创建 api-gateway模块 在pom.xml中添加相关依赖 两种不同的配置路由方式 使用yml配置 使用Ja ...

  8. Spring Cloud入门-Config分布式配置中心(Hoxton版本)

    文章目录 Spring Cloud入门系列汇总 摘要 Spring Cloud Config 简介 在Git仓库中准备配置信息 配置仓库目录结构 master分支下的配置信息 dev分支下的配置信息 ...

  9. Spring Cloud 入门 ---- Security 整合 Oauth2 认证授权【随笔】

    Spring Cloud Security Oauth2 文档参考:https://docs.spring.io/spring-security/site/docs/5.4.1/reference/h ...

最新文章

  1. Go 学习笔记(74)— Go 标准库之 unsafe
  2. p4.pm p4python p4perl p4api 的使用方法
  3. Ajax/CSS表格设计汇集
  4. php获取服务器名称,PHP 获取服务器详细信息
  5. 培养用户习惯才是软件的唯一出路!
  6. 【 D3.js 入门系列 --- 7 】 理解 update, enter, exit 的使用
  7. 【原创】自己动手写控件----XSmartNote控件
  8. cpu频率_CPU频率的提升到底会产生哪些影响?
  9. Abaqus槽钢杆受力有限元分析
  10. 纯css 箭头,纯CSS实现小箭头的案例
  11. 自己组装nas服务器万兆,万兆网络、装M.2 SSD的NAS服务器
  12. Java判断上海自来水来自海上_JavaAPI
  13. C++11 decay
  14. 开发技巧--发送手机验证码接口调用
  15. UGUI文本颜色渐变
  16. 数控机床设备物联网远程控制解决方案
  17. JavaScript阻塞与非阻塞
  18. 机器学习-朴素贝叶斯算法
  19. 数据库表赋权给指定用户
  20. [BUUCTF]PWN——mrctf2020_shellcode_revenge(可见字符shellcode)

热门文章

  1. vue项目中打印数据或表格(使用第三方依赖print-js)
  2. NRF51822开发笔记-5.nRF51822裸机实验GPIO输出驱动LED
  3. ibm bpm实战指南_IBM Security Network Protection实施指南(针对技术人员的XGS)
  4. 有道互动内容引擎 Ceramics 的业务实践
  5. 外网ssh连接树莓派【无需公网IP】
  6. mysql中查询分析器Explain的type的解释
  7. 在服务器上搭建 Chevereto 图床
  8. linux的作业控制(job control)
  9. iPhone手机语音翻译怎么操作?中英文对话原来如此轻松,太赞了
  10. [10.17日更新]各大互联网公司架构演进之路汇总