在之前的OAuth实现中,令牌通常存储在内存中,这对程序扩展不利。为解决此问题,可以将令牌存储在数据库或Redis中。本文将介绍如何实现这两种存储方式。
非JWT令牌的存储
数据库存储(JdbcTokenStore)
首先,创建必要的数据库表:
CREATE TABLE access_tokens (
token_id VARCHAR(256),
token BLOB,
auth_id VARCHAR(256),
username VARCHAR(256),
client_id VARCHAR(256),
auth_data BLOB,
refresh_token VARCHAR(256)
);
CREATE TABLE refresh_tokens (
token_id VARCHAR(256),
token BLOB,
auth_data BLOB
);
接着配置数据源和TokenStore:
@Autowired
private DataSource dataSource;
@Bean
public TokenStore tokenStorage() {
return new JdbcTokenStore(dataSource);
}
添加jdbc依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
Redis存储(RedisTokenStore)
添加redis依赖并配置连接:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
配置类示例:
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
RedisTemplate template = new RedisTemplate<>();
template.setConnectionFactory(factory);
// 配置序列化器等...
return template;
}
}
配置token存储:
@Autowired
private RedisConnectionFactory redisFactory;
@Bean
public TokenStore tokenStorage() {
return new RedisTokenStore(redisFactory);
}
JWT令牌的使用与存储
对于JWT令牌,除了存储之外,还需要配置签名密钥:
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey("your_secret_key");
return converter;
}
在认证服务器配置中加入JWT转换器和TokenStore:
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints
.authenticationManager(authenticationManager)
.authorizationCodeServices(authorizationCodeServices())
.accessTokenConverter(accessTokenConverter())
.tokenStore(tokenStorage());
}
通过以上步骤,我们完成了Token令牌的高效存储与获取。