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

你的名字 2021-09-21 01:28 338阅读 0赞

文章目录

    • 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中添加相关依赖:

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.springframework.cloud</groupId>
  7. <artifactId>spring-cloud-starter-oauth2</artifactId>
  8. </dependency>
  9. <dependency>
  10. <groupId>org.springframework.cloud</groupId>
  11. <artifactId>spring-cloud-starter-security</artifactId>
  12. </dependency>

在application.yml中进行配置:

  1. server:
  2. port: 9501
  3. servlet:
  4. session:
  5. cookie:
  6. # 防止cookie冲突,冲突会导致登录验证不通过
  7. name: OAUTH2-CLIENT-SESSIONID
  8. oauth2-service-url: http://localhost:9401
  9. spring:
  10. application:
  11. name: oauth2-client
  12. security:
  13. # 与oauth2-server对应的配置
  14. oauth2:
  15. client:
  16. client-id: admin
  17. client-secret: admin123456
  18. user-authorization-uri: ${ oauth2-service-url}/oauth/authorize
  19. access-token-uri: ${ oauth2-service-url}/oauth/token
  20. resource:
  21. jwt:
  22. key-uri: ${ oauth2-service-url}/oauth/token_key

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

  1. @EnableOAuth2Sso
  2. @SpringBootApplication
  3. public class Oauth2ClientApplication {
  4. public static void main(String[] args) {
  5. SpringApplication.run(Oauth2ClientApplication.class, args);
  6. }
  7. }

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

  1. @RestController
  2. @RequestMapping("/user")
  3. public class UserController {
  4. @GetMapping("/getCurrentUser")
  5. public Object getCurrentUser(Authentication authentication) {
  6. return authentication;
  7. }
  8. }

修改授权服务器配置

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

  1. @Configuration
  2. @EnableAuthorizationServer
  3. public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
  4. //以上省略一堆代码...
  5. @Override
  6. public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
  7. clients.inMemory()
  8. // 配置client_id
  9. .withClient("admin")
  10. // 配置client_secret
  11. .secret(passwordEncoder.encode("admin123456"))
  12. // 配置访问token的有效期
  13. .accessTokenValiditySeconds(3600)
  14. // 配置刷新token的有效期
  15. .refreshTokenValiditySeconds(864000)
  16. // 配置redirect_uri,用于授权成功后的跳转
  17. // .redirectUris("http://www.baidu.com")
  18. // 单点登录时配置
  19. .redirectUris("http://localhost:9501/login")
  20. // 自动授权配置
  21. // .autoApprove(true)
  22. // 配置申请的权限范围
  23. .scopes("all")
  24. // 配置grant_type,表示授权类型
  25. .authorizedGrantTypes("authorization_code", "password", "refresh_token");
  26. }
  27. @Override
  28. public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
  29. // 获取密钥需要身份认证,使用单点登录时必须配置
  30. security.tokenKeyAccess("isAuthenticated()");
  31. }
  32. }

网页单点登录演示

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

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

在这里插入图片描述

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

在这里插入图片描述

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

在这里插入图片描述

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

  1. @Configuration
  2. @EnableAuthorizationServer
  3. public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
  4. //以上省略一堆代码...
  5. @Override
  6. public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
  7. clients.inMemory()
  8. // 配置client_id
  9. .withClient("admin")
  10. // 配置client_secret
  11. .secret(passwordEncoder.encode("admin123456"))
  12. // 配置访问token的有效期
  13. .accessTokenValiditySeconds(3600)
  14. // 配置刷新token的有效期
  15. .refreshTokenValiditySeconds(864000)
  16. // 配置redirect_uri,用于授权成功后的跳转
  17. // .redirectUris("http://www.baidu.com")
  18. // 单点登录时配置
  19. .redirectUris("http://localhost:9501/login")
  20. // 自动授权配置
  21. .autoApprove(true)
  22. // 配置申请的权限范围
  23. .scopes("all")
  24. // 配置grant_type,表示授权类型
  25. .authorizedGrantTypes("authorization_code", "password", "refresh_token");
  26. }
  27. }

调用接口单点登录演示

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

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

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

在这里插入图片描述

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

在这里插入图片描述

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

在这里插入图片描述

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

在这里插入图片描述

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

  1. {
  2. "authorities": [{
  3. "authority": "admin"
  4. }],
  5. "details": {
  6. "remoteAddress": "0:0:0:0:0:0:0:1",
  7. "sessionId": "6F5A553BB678C7272145FF9FF2A5D8F4",
  8. "tokenValue": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJqb3Vyd29uIiwic2NvcGUiOlsiYWxsIl0sImV4cCI6MTU3NzY4OTc2NiwiYXV0aG9yaXRpZXMiOlsiYWRtaW4iXSwianRpIjoiZjAwYjVkMGUtNjFkYi00YjBmLTkyNTMtOWQxZDYwOWM4ZWZmIiwiY2xpZW50X2lkIjoiYWRtaW4iLCJlbmhhbmNlIjoiZW5oYW5jZSBpbmZvIn0.zdgFTWJt3DnAsjpQRU6rNA_iM7gVHX7E9bCyF73MOSM",
  9. "tokenType": "bearer",
  10. "decodedDetails": null
  11. },
  12. "authenticated": true,
  13. "userAuthentication": {
  14. "authorities": [{
  15. "authority": "admin"
  16. }],
  17. "details": null,
  18. "authenticated": true,
  19. "principal": "jourwon",
  20. "credentials": "N/A",
  21. "name": "jourwon"
  22. },
  23. "clientOnly": false,
  24. "oauth2Request": {
  25. "clientId": "admin",
  26. "scope": ["all"],
  27. "requestParameters": {
  28. "client_id": "admin"
  29. },
  30. "resourceIds": [],
  31. "authorities": [],
  32. "approved": true,
  33. "refresh": false,
  34. "redirectUri": null,
  35. "responseTypes": [],
  36. "extensions": { },
  37. "grantType": null,
  38. "refreshTokenRequest": null
  39. },
  40. "principal": "jourwon",
  41. "credentials": "",
  42. "name": "jourwon"
  43. }

oauth2-client添加权限校验

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

  1. @Configuration
  2. @EnableGlobalMethodSecurity(prePostEnabled = true)
  3. @Order(101)
  4. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  5. }

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

  1. @RestController
  2. @RequestMapping("/user")
  3. public class UserController {
  4. @PreAuthorize("hasAuthority('admin')")
  5. @GetMapping("/auth/admin")
  6. public Object adminAuth() {
  7. return "Has admin auth!";
  8. }
  9. }

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

在这里插入图片描述

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

在这里插入图片描述

使用到的模块

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

项目源码地址

GitHub项目源码地址

发表评论

表情:
评论列表 (有 0 条评论,338人围观)

还没有评论,来说两句吧...

相关阅读