详解springSecurity之令牌存储TokenStore实现的4种方式
haoteby 2025-06-23 19:10 26 浏览
前言
使用springSecurity作权限控制时,登陆成功会创建对应授权信息,然后通过对应的TokenStore实现把对应的授权信息保存起来,当显示用户访问对应保护接口时就会根据客户端传入的token获取认证信息。
我们先看下TokenStore接口定义:
public interface TokenStore {
/**
* Read the authentication stored under the specified token value.
*
* @param token The token value under which the authentication is stored.
* @return The authentication, or null if none.
*/
OAuth2Authentication readAuthentication(OAuth2AccessToken token);
/**
* Read the authentication stored under the specified token value.
*
* @param token The token value under which the authentication is stored.
* @return The authentication, or null if none.
*/
OAuth2Authentication readAuthentication(String token);
/**
* Store an access token.
*
* @param token The token to store.
* @param authentication The authentication associated with the token.
*/
void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication);
/**
* Read an access token from the store.
*
* @param tokenValue The token value.
* @return The access token to read.
*/
OAuth2AccessToken readAccessToken(String tokenValue);
/**
* Remove an access token from the store.
*
* @param token The token to remove from the store.
*/
void removeAccessToken(OAuth2AccessToken token);
/**
* Store the specified refresh token in the store.
*
* @param refreshToken The refresh token to store.
* @param authentication The authentication associated with the refresh token.
*/
void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication);
/**
* Read a refresh token from the store.
*
* @param tokenValue The value of the token to read.
* @return The token.
*/
OAuth2RefreshToken readRefreshToken(String tokenValue);
/**
* @param token a refresh token
* @return the authentication originally used to grant the refresh token
*/
OAuth2Authentication readAuthenticationForRefreshToken(OAuth2RefreshToken token);
/**
* Remove a refresh token from the store.
*
* @param token The token to remove from the store.
*/
void removeRefreshToken(OAuth2RefreshToken token);
/**
* Remove an access token using a refresh token. This functionality is necessary so refresh tokens can't be used to
* create an unlimited number of access tokens.
*
* @param refreshToken The refresh token.
*/
void removeAccessTokenUsingRefreshToken(OAuth2RefreshToken refreshToken);
/**
* Retrieve an access token stored against the provided authentication key, if it exists.
*
* @param authentication the authentication key for the access token
*
* @return the access token or null if there was none
*/
OAuth2AccessToken getAccessToken(OAuth2Authentication authentication);
/**
* @param clientId the client id to search
* @param userName the user name to search
* @return a collection of access tokens
*/
Collection<OAuth2AccessToken> findTokensByClientIdAndUserName(String clientId, String userName);
/**
* @param clientId the client id to search
* @return a collection of access tokens
*/
Collection<OAuth2AccessToken> findTokensByClientId(String clientId);
}
在springSecurity中TokenStore实现有4种,分别是:
- InMemoryTokenStore(保存本地内存)
- JdbcTokenStore(保存到数据库)
- JwkTokenStore(全部信息返回到客户端
- RedisTokenStore(保存到redis)
由于认证调用的频率,一般推荐使用RedisTokenStore或者JwkTokenStore两种。
一、InMemoryTokenStore
1.1.概要
这个是OAuth2默认采用的实现方式。在单服务上可以体现出很好特效(即并发量不大,并且它在失败的时候不会进行备份),大多项目都可以采用此方法。根据名字就知道了,是存储在内存中,毕竟存在内存,而不是磁盘中,调试简易。但是,实际中很少使用,因为没有持久化,会导致数据丢失。
1.2.实现
既然InMemoryTokenStore是OAuth2默认实现,那么就不需要我们再去配置,直接调用即可。
1.3.代码调用
在认证服务端加入配置。
@Autowired(required = false)private TokenStore inMemoryTokenStore;/** * 端点(处理入口) */@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.tokenStore(inMemoryTokenStore); ....}
二、JdbcTokenStore
2.1.概要
这个是基于JDBC的实现,令牌(Access Token)会保存到数据库。这个方式,可以在多个服务之间实现令牌共享。因为是保存到数据库,而且是必须有OAuth2默认的表结构:oauth_access_token。
2.2.实现
1)创建库表,因此OAuth2默认给出了表结构:
Drop table if exists oauth_access_token;
create table oauth_access_token (
create_time timestamp default now(),
token_id VARCHAR(255),
token BLOB,
authentication_id VARCHAR(255),
user_name VARCHAR(255),
client_id VARCHAR(255),
authentication BLOB,
refresh_token VARCHAR(255)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Drop table if exists oauth_refresh_token;
create table oauth_refresh_token (
create_time timestamp default now(),
token_id VARCHAR(255),
token BLOB,
authentication BLOB
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
复制代码
对应JdbcTokenStore源码中其实有很多操作是关于此表的,感兴趣的可以看下。
2).配置JdbcTokenStore
在对应配置类中声明即可,目的是将JDBCTokenStore实例化到Spring容器中。
@Autowired
private DataSource dataSource;
/**
* jdbc token 配置
*/
@Bean
public TokenStore jdbcTokenStore() {
Assert.state(dataSource != null, "DataSource must be provided");
return new JdbcTokenStore(dataSource);
}
2.3.代码调用
@Autowired(required = false)
private TokenStore jdbcTokenStore;
/**
* 端点(处理入口)
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(jdbcTokenStore);
....
}
三、JwtTokenStore
3.1.概要
jwt全称 JSON Web Token。这个实现方式不用管如何进行存储(内存或磁盘),因为它可以把相关信息数据编码存放在令牌里。JwtTokenStore 不会保存任何数据,但是它在转换令牌值以及授权信息方面与 DefaultTokenServices 所扮演的角色是一样的。
3.2.实现
既然jwt是将信息存放在令牌中,那么就得考虑其安全性,因此,OAuth2提供了JwtAccessTokenConverter实现,添加jwtSigningKey,以此生成秘钥,以此进行签名,只有jwtSigningKey才能获取信息。
/**
* jwt Token 配置, matchIfMissing = true
*
* @author : CatalpaFlat
*/
@Configuration
public class JwtTokenConfig {
private final Logger logger = LoggerFactory.getLogger(JwtTokenConfig.class);
@Value("${default.jwt.signing.key}")
private String defaultJwtSigningKey;
@Autowired
private CustomYmlConfig customYmlConfig;
public JwtTokenConfig() {logger.info("Loading JwtTokenConfig ...");}
@Bean
public TokenStore jwtTokenStore() {
return new JwtTokenStore(jwtAccessTokenConverter());
}
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
String jwtSigningKey = customYmlConfig.getSecurity().getOauth2s().getOuter().getJwtSigningKey();
Assert.state(StringUtils.isBlank(jwtSigningKey), "jwtSigningKey is not configured");
//秘签
jwtAccessTokenConverter.setSigningKey(StringUtils.isBlank(jwtSigningKey) ? defaultJwtSigningKey : jwtSigningKey);
return jwtAccessTokenConverter;
}
}
3.3.代码调用
@Autowired(required = false)
private TokenStore jwtTokenStore;
@Autowired(required = false)
private JwtAccessTokenConverter jwtAccessTokenConverter;
/**
* 端点(处理入口)
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(jwtTokenStore)
.accessTokenConverter(jwtAccessTokenConverter);
....
}
四、RedisTokenStore
4.1.概要
顾名思义,就是讲令牌信息存储到redis中。首先必须保证redis连接正常。
4.2.实现
@Autowired
private RedisConnectionFactory redisConnectionFactory;
/**
* redis token 配置
*/
@Bean
public TokenStore redisTokenStore() {
return new RedisTokenStore(redisConnectionFactory);
}
4.3.代码调用
@Autowired(required = false)
private TokenStore redisTokenStore;
/**
* 端点(处理入口)
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(redisTokenStore);
....
}
以上为4种实现方式,在实际工作中可以按照具体情况进行调整。
以上为全部内容。
相关推荐
- 如何为MySQL服务器和客户机启用SSL?
-
用户想要与MySQL服务器建立一条安全连接时,常常依赖VPN隧道或SSH隧道。不过,获得MySQL连接的另一个办法是,启用MySQL服务器上的SSL封装器(SSLwrapper)。这每一种方法各有其...
- k8s 证书问题排查_k8s dashboard 证书
-
从去年开始一些老项目上陆陆续续出现一些列的证书问题,(证书原理这里就不说了,官方文档一堆)多数刚开始的表现就是节点的kubelet服务起不来,节点状态NotReady表现日志如下failed...
- 企业级网络互通方案:云端OpenVPN+爱快路由器+Win11互联实战
-
企业级网络互通方案:OpenVPN搭建公有云+爱快路由器+Win11三地互联实战指南「安全高效」三地局域网秒变局域网实施环境说明...
- OpenV** Server/Client配置文件详解
-
Server配置详解...
- 接口基础认知:关键信息与合规前提
-
1.核心技术参数(必记)...
- S交换机通过SSH登录设备配置示例(RADIUS认证+本地认证独立)
-
说明:●本示例只介绍设备的认证相关配置,请同时确保已在RADIUS服务器上做了相关配置,如设备地址、共享密钥、创建用户等配置。●通过不同的管理域来实现RADIUS认证与本地认证两种方式同时使用,两...
- SSL证书如何去除私钥密码保护_ssl证书怎么取消
-
有时候我们在生成证书的时候可以加入了密码保护。然后申请到证书安装到了web服务器。但是这样可能会带来麻烦。每次重启apache或者nginx的时候,都需要输入密码。那么SSL证书如何去除私钥密码保护。...
- SSL证书基础知识与自签名证书生成指南
-
一、证书文件类型解析...
- S交换机通过SSH登录设备配置示例(RADIUS认证)
-
说明:本示例只介绍设备的认证相关配置,请同时确保已在RADIUS服务器上做了相关配置,如设备地址、共享密钥、创建用户等配置。假设已在RADIUS服务器上创建了用户名yc123,密码test#123。对...
- HTTPS是什么?加密原理和证书。SSL/TLS握手过程
-
秘钥的产生过程非对称加密...
- HTTPS TLS握手流程_进行tls握手
-
1.客户端向服务器发送`ClientHello`消息,包括支持的TLS版本、加密套件、随机数等信息。2.服务器收到`ClientHello`消息后,解析其中的信息,并根据配置选择一个加密套件。3....
- Spring Boot 单点登录(SSO)实现_spring boot 单点登录jwt
-
SpringBoot单点登录(SSO)实现全指南单点登录(SingleSign-On,SSO)是一种身份验证机制,允许用户使用一组凭证登录多个相关但独立的系统。在微服务架构和企业级系统中,SS...
- 源码分享:在pdf上加盖电子签章_pdf如何加盖电子公章
-
在pdf上加盖电子签章,并不是只是加个印章图片,。而是要使用一对密钥中的私钥对文件进行签字。为啥要用私钥呢?很简单,因为公钥是公开的,其他人才可以用公钥为你证明,这个文件是你签的。这就是我们常说的:私...
- 微信支付商户API证书到期 怎么更换
-
微信支付商户API证书到期更换是一个非常重要的操作,需要仔细按照流程进行。如果证书过期,所有通过API的支付、退款等操作都会失败,将直接影响您的业务。请按照以下详细步骤进行操作:重要前提:分清...