Spring Cloud入门-Oauth2授权之JWT集成(Hoxton版本)
文章目录
- Spring Cloud入门系列汇总
- 摘要
- JWT简介
- JWT的组成
- JWT实例
- 创建oauth2-jwt-server模块
- oauth2中存储令牌的方式
- 使用Redis存储令牌
- 使用JWT存储令牌
- 扩展JWT中存储的内容
- Java中解析JWT中的内容
- 刷新令牌
- 使用到的模块
- 项目源码地址
项目使用的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还可以实现更多功能,比如使用JWT令牌存储信息,刷新令牌功能,本文将对其结合JWT使用进行详细介绍。
JWT简介
JWT是JSON WEB TOKEN的缩写,它是基于 RFC 7519 标准定义的一种可以安全传输的的JSON对象,由于使用了数字签名,所以是可信任和安全的。
JWT的组成
JWT token的格式:header.payload.signature;
header中用于存放签名的生成算法;
{"alg": "HS256","typ": "JWT"
}
payload中用于存放数据,比如过期时间、用户名、用户所拥有的权限等;
{"user_name": "jourwon","scope": ["all"],"exp": 1577678449,"authorities": ["admin"],"jti": "618cda6a-dfce-4966-b0df-00607f693ab5","client_id": "admin"
}
signature为以header和payload生成的签名,一旦header和payload被篡改,验证将失败。
JWT实例
这是一个JWT的字符串:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJqb3Vyd29uIiwic2NvcGUiOlsiYWxsIl0sImV4cCI6MTU3NzY3Nzc2MywiYXV0aG9yaXRpZXMiOlsiYWRtaW4iXSwianRpIjoiMGY4NmE2ODUtZDIzMS00M2E0LWJhZjYtNzAwMmE0Yzg1YmM1IiwiY2xpZW50X2lkIjoiYWRtaW4iLCJlbmhhbmNlIjoiZW5oYW5jZSBpbmZvIn0.RLrkBQEOdCikiz0SsJ8ZsVcxk8GkAyKsOj5fZytgNF8
可以在该网站上获得解析结果:https://jwt.io/
创建oauth2-jwt-server模块
该模块只是对oauth2-server模块的扩展,直接复制过来扩展下下即可。
oauth2中存储令牌的方式
在上一节中我们都是把令牌存储在内存中的,这样如果部署多个服务,就会导致无法使用令牌的问题。 Spring Cloud Security中有两种存储令牌的方式可用于解决该问题,一种是使用Redis来存储,另一种是使用JWT来存储。
使用Redis存储令牌
在pom.xml中添加Redis相关依赖:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<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中添加redis相关配置:
server:port: 9401spring:application:name: oauth2-jwt-serverredis:# redis相关配置host: 10.172.0.201database: 0
添加在Redis中存储令牌的配置:
@Configuration
public class RedisTokenStoreConfig {@Autowiredprivate RedisConnectionFactory redisConnectionFactory;@Beanpublic TokenStore redisTokenStore() {return new RedisTokenStore(redisConnectionFactory);}}
在授权服务器配置中指定令牌的存储策略为Redis:
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {@Autowiredprivate PasswordEncoder passwordEncoder;@Autowiredprivate AuthenticationManager authenticationManager;@Autowiredprivate UserService userService;@Autowired@Qualifier("redisTokenStore")private TokenStore tokenStore;/*** 使用密码模式需要配置*/@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) {endpoints.authenticationManager(authenticationManager).userDetailsService(userService)//配置令牌存储策略.tokenStore(tokenStore);}//省略代码...
}
运行项目后使用密码模式来获取令牌,访问如下地址:http://localhost:9401/oauth/token
进行获取令牌操作,可以发现令牌已经被存储到Redis中。
使用JWT存储令牌
添加使用JWT存储令牌的配置:
@Configuration
public class JwtTokenStoreConfig {@Bean@Primarypublic TokenStore jwtTokenStore() {return new JwtTokenStore(jwtAccessTokenConverter());}@Beanpublic JwtTokenEnhancer jwtTokenEnhancer() {return new JwtTokenEnhancer();}@Beanpublic JwtAccessTokenConverter jwtAccessTokenConverter() {JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();// 配置jwt使用的密钥jwtAccessTokenConverter.setSigningKey("test_key");return jwtAccessTokenConverter;}}
在授权服务器配置中指定令牌的存储策略为JWT:
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {@Autowiredprivate PasswordEncoder passwordEncoder;@Autowiredprivate AuthenticationManager authenticationManager;@Autowiredprivate UserService userService;@Autowired@Qualifier("jwtTokenStore")private TokenStore tokenStore;@Autowiredprivate JwtAccessTokenConverter jwtAccessTokenConverter;@Autowiredprivate JwtTokenEnhancer jwtTokenEnhancer;/*** 使用密码模式需要配置*/@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) {endpoints.authenticationManager(authenticationManager).userDetailsService(userService)//配置令牌存储策略.tokenStore(tokenStore) .accessTokenConverter(jwtAccessTokenConverter);}//省略代码...
}
运行项目后使用密码模式来获取令牌,访问如下地址:http://localhost:9401/oauth/token
发现获取到的令牌已经变成了JWT令牌,将access_token拿到https://jwt.io/ 网站上去解析下可以获得其中内容。
{"exp": 1577678092,"user_name": "jourwon","authorities": ["admin"],"jti": "87db4bdf-2936-420d-87b9-fb580e255a4d","client_id": "admin","scope": ["all"]
}
扩展JWT中存储的内容
有时候我们需要扩展JWT中存储的内容,这里我们在JWT中扩展一个key为
enhance
,value为enhance info
的数据。
继承TokenEnhancer实现一个JWT内容增强器:
public class JwtTokenEnhancer implements TokenEnhancer {@Overridepublic OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {Map<String, Object> info = new HashMap<>();info.put("enhance", "enhance info");((DefaultOAuth2AccessToken) oAuth2AccessToken).setAdditionalInformation(info);return oAuth2AccessToken;}}
创建一个JwtTokenEnhancer实例:
@Configuration
public class JwtTokenStoreConfig {//省略代码...@Beanpublic JwtTokenEnhancer jwtTokenEnhancer() {return new JwtTokenEnhancer();}
}
在授权服务器配置中配置JWT的内容增强器:
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {@Autowiredprivate PasswordEncoder passwordEncoder;@Autowiredprivate AuthenticationManager authenticationManager;@Autowiredprivate UserService userService;@Autowired@Qualifier("jwtTokenStore")private TokenStore tokenStore;@Autowiredprivate JwtAccessTokenConverter jwtAccessTokenConverter;@Autowiredprivate JwtTokenEnhancer jwtTokenEnhancer;/*** 使用密码模式需要配置** @param endpoints* @throws Exception*/@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();List<TokenEnhancer> delegates = new ArrayList<>();// 配置jwt内容增强器delegates.add(jwtTokenEnhancer);delegates.add(jwtAccessTokenConverter);tokenEnhancerChain.setTokenEnhancers(delegates);endpoints.authenticationManager(authenticationManager).userDetailsService(userService)// 配置令牌存储策略.tokenStore(tokenStore).accessTokenConverter(jwtAccessTokenConverter).tokenEnhancer(tokenEnhancerChain);}// 省略代码...
}
运行项目后使用密码模式来获取令牌,之后对令牌进行解析,发现已经包含扩展的内容。
{"user_name": "jourwon","scope": ["all"],"exp": 1577678449,"authorities": ["admin"],"jti": "618cda6a-dfce-4966-b0df-00607f693ab5","client_id": "admin","enhance": "enhance info"
}
Java中解析JWT中的内容
如果我们需要获取JWT中的信息,可以使用一个叫jjwt的工具包。
在pom.xml中添加相关依赖:
<dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt</artifactId><version>0.9.1</version>
</dependency>
修改UserController类,使用jjwt工具类来解析Authorization头中存储的JWT内容。
@RestController
@RequestMapping("/user")
public class UserController {@GetMapping("/getCurrentUser")public Object getCurrentUser(Authentication authentication, HttpServletRequest request) {String header = request.getHeader("Authorization");String token = StrUtil.subAfter(header, "bearer", false);return Jwts.parser().setSigningKey("test_key".getBytes(StandardCharsets.UTF_8)).parseClaimsJws(token).getBody();}}
将令牌放入Authorization
头中,访问如下地址获取信息:http://localhost:9401/user/getCurrentUser
刷新令牌
在Spring Cloud Security 中使用oauth2时,如果令牌失效了,可以使用刷新令牌通过refresh_token的授权模式再次获取access_token。
只需修改授权服务器的配置,添加refresh_token的授权模式即可。
@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");}
}
使用刷新令牌模式来获取新的令牌,访问如下地址:http://localhost:9401/oauth/token
使用到的模块
springcloud-learning
└── oauth2-jwt-server -- 使用jwt的oauth2授权测试服务
项目源码地址
GitHub项目源码地址
Spring Cloud入门-Oauth2授权之JWT集成(Hoxton版本)相关推荐
- Spring Cloud入门-Oauth2授权之基于JWT完成单点登录(Hoxton版本)
文章目录 Spring Cloud入门系列汇总 摘要 单点登录简介 创建oauth2-client模块 修改授权服务器配置 网页单点登录演示 调用接口单点登录演示 oauth2-client添加权限校 ...
- Spring Cloud入门-Seata处理分布式事务问题(Hoxton版本)
我们先从官网下载seata-server,这里下载的是seata-server-1.0.0.zip,下载地址:https://github.com/seata/seata/releases 这里我们使 ...
- Spring Cloud入门-Admin服务监控中心(Hoxton版本)
文章目录 Spring Cloud入门系列汇总 摘要 Spring Boot Admin 简介 创建admin-server模块 创建admin-client模块 监控信息演示 结合注册中心使用 修改 ...
- Spring Cloud入门-Sentinel实现服务限流、熔断与降级(Hoxton版本)
文章目录 Spring Cloud入门系列汇总 摘要 Sentinel简介 安装Sentinel控制台 创建sentinel-service模块 限流功能 创建RateLimitController类 ...
- Spring Cloud入门-Ribbon服务消费者(Hoxton版本)
文章目录 Spring Cloud入门系列汇总 摘要 Ribbon简介 RestTemplate的使用 GET请求方法 getForObject方法 getForEntity方法 POST请求方法 p ...
- Spring Cloud入门-Nacos实现注册和配置中心(Hoxton版本)
文章目录 Spring Cloud入门系列汇总 摘要 Nacos简介 使用Nacos作为注册中心 安装并运行Nacos 创建应用注册到Nacos 负载均衡功能 使用Nacos作为配置中心 创建naco ...
- Spring Cloud入门-Gateway服务网关(Hoxton版本)
文章目录 Spring Cloud入门系列汇总 摘要 Gateway 简介 相关概念 创建 api-gateway模块 在pom.xml中添加相关依赖 两种不同的配置路由方式 使用yml配置 使用Ja ...
- Spring Cloud入门-Config分布式配置中心(Hoxton版本)
文章目录 Spring Cloud入门系列汇总 摘要 Spring Cloud Config 简介 在Git仓库中准备配置信息 配置仓库目录结构 master分支下的配置信息 dev分支下的配置信息 ...
- Spring Cloud 入门 ---- Security 整合 Oauth2 认证授权【随笔】
Spring Cloud Security Oauth2 文档参考:https://docs.spring.io/spring-security/site/docs/5.4.1/reference/h ...
- gateway oauth2 对称加密_深入理解Spring Cloud Security OAuth2及JWT
因项目需要,需要和三方的oauth2服务器进行集成.网上关于spring cloud security oauth2的相关资料,一般都是讲如何配置,而能把这块原理讲透彻的比较少,这边自己做一下总结和整 ...
最新文章
- 人工智能项目的六投三不投
- Spring boot依赖版本管理
- 我参与阿里巴巴 ASoC-Seata 的一些感悟
- Multisim14.0 安装教程
- Web前端主要学什么?这些知识要掌握
- 电脑设置访问苹果服务器未响应,苹果连接电脑没反应,教您苹果连接电脑没反应怎么解决...
- MySQL笔记-查询进程列表(查客户端IP、使用的用户、当前状态、ID号、使用的库)及断开客户端连接
- Skeljs – 用于构建响应式网站的前端开发框架
- 想减少代码量,快设置一个有感知的 Aware Spring Bean
- oracle 空值的排序问题 (转载),sqlserver、oracle数据库排序空值null问题解决办法
- virus.win32.xorer病毒
- 当归饮(茶):治疗血虚
- 利用JS实现 TABLE的分页
- java数据透视表_Java 创建 Excel 数据透视表
- 校园二手交易平台小程序《云开发演示》
- 硕士论文查重原理是什么?
- php-fpm 端口号,PHP-FPM 配置说明
- linux查看java虚拟机内存_JVM:查看java内存情况命令
- STM32基础11--模数转换(ADC)
- Linux下移动硬盘,创建windows,ntfs分区并挂载