SpringCloud微服务——基于security+oauth2的安全保护(四):授权服务之redis存储token


SpringCloud微服务——基于security+oauth2的安全保护(二):授权服务该文中,存储token信息使用的是jdbc的方式。这里介绍一种使用redis存储的方法(本文是建立在 授权服务之上的,以它为基础改造)。
为了多样化,就不删除以前的功能了,可以通过配置来决定使用哪个。

加入jar包

以前的jar包不要动,加入redis的就可以了。

<!-- redis start -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- redis end -->

加入配置

在配置文件(或者配置中心)加入配置:(注意:注释和配置不要写在同一行,这里是直接从配置中心拷贝的

#redis链接信息
spring.redis.database=0                        # Redis数据库索引(默认为0)
spring.redis.host=xxxxxxxx                     # Redis服务器地址
spring.redis.port=6379                         # Redis服务器连接端口
spring.redis.password=xxxx                     # Redis服务器连接密码(默认为空)
spring.redis.jedis.pool.max-active=8           # 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1            # 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-idle=8             # 连接池中的最大空闲连接
spring.redis.jedis.pool.min-idle=0             # 连接池中的最小空闲连接
spring.redis.timeout=1000                      # 连接超时时间(毫秒)

#token存储方式
fyk.authorization.token-store=redis			   #token的存储方式,可选值为:redis,jdbc,jwt_sy,jwt_asy;默认为jdbc

修改授权服务配置

在OAuth2AuthorizationConfig类中修改代码如下:
加入配置:主要就是为了接受配置文件中的配置信息,也就是上一步中的fyk.authorization.token-store=reids配置。

/**
 * token的存储方式
 */
@Value("${fyk.authorization.token-store:jdbc}")
private String tokenStore;

然后修改getTokenStore方法:

@Bean
public TokenStore getTokenStore() {
	if(REDIS_STORE.equalsIgnoreCase(tokenStore)){
		RedisTokenStore redisTokenStore = new RedisTokenStore(redisConnectionFactory);
		redisTokenStore.setAuthenticationKeyGenerator(authentication -> "FYK"+UUID.randomUUID().toString().replace("-", ""));
        return redisTokenStore;
	}else {
		JdbcTokenStore jdbcTokenStore = new JdbcTokenStore(dataSource);
		jdbcTokenStore.setAuthenticationKeyGenerator(authentication -> "FYK"+UUID.randomUUID().toString().replace("-", ""));
		return jdbcTokenStore;
	}
}

到这里,启动项目,现在token的存储就不再jdbc了,而是使用了redis。

问题

如果按照上面的步骤来,如果出现了错误:
java.lang.NoSuchMethodError: org.springframework.data.redis.connection.RedisConnection.set([B[B)V
这说明版本有问题,解决方案是,将oauth2的版本升级到2.3.3,即在pom文件中,加入:

<!-- oauth2 start -->
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.security.oauth</groupId>
	<artifactId>spring-security-oauth2</artifactId>
	<!-- 指明版本,解决redis存储出现的问题:java.lang.NoSuchMethodError: org.springframework.data.redis.connection.RedisConnection.set([B[B)V问题 -->
	<version>2.3.3.RELEASE</version>
</dependency>
<!-- oauth2 end -->
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值