详解springSecurity之令牌存储TokenStore实现的4种方式
haoteby 2025-06-23 19:10 6 浏览
前言
使用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种实现方式,在实际工作中可以按照具体情况进行调整。
以上为全部内容。
相关推荐
- 谷歌开源大模型评测框架正式发布,AI模型评测难题迎刃而解
-
近日科技巨头谷歌正式推出其开源大模型评测框架LMEval,这一创新工具为全球AI开发者和企业提供了标准化的模型评估解决方案。LMEval的发布不仅标志着AI模型评测迈入透明化时代,更通过多项核心技术...
- Android 开发中文引导-动画和图形概述
-
安卓系统提供了各种强大的API,用来将动画应用于界面元素和自定义2D和3D图形的绘制当中。下面的小节大概的描述了可用的API和系统功能并帮助你决定那个方案最适合你的需要。动画安卓框架提供了两种动画系统...
- Qt5 C++入门教程-第12章 绘图(QPainter)
-
QPainter类在Qt5中进行绘图时起着重要作用。绘图操作是通过QPainter类在响应paintEvent方法时完成的。线条在第一个示例中,我们在窗口的客户区绘制了一些线条。line...
- 文创测评︱《如意琳琅图籍》:本土原创解谜书的胜利?
-
设想这样一个场景,你打开一本书,就化身为乾隆三十六年紫禁城中的画画人周本,有一天你在故纸堆中找到一本神秘的《如意琳琅图籍》,踏上寻宝旅程,历经各种离奇复杂的故事……这是故宫与奥秘之家联手打造的创意解谜...
- gif动图制作攻略!快快收藏(求gif制作的动图)
-
有事没事斗图玩是当下人们乐此不疲的事情,手里的gif动图也渐渐成为了人们抬杠互怼的一大资本。好有趣,好炫酷,gif是怎么做出来的?我也想做。什么?你不会?没关系,我来教你!首先介绍一下制作gif动图需...
- eduis未能初始化界面 无法启动 问题解决办法
-
1.如果edius安装后启动后出现failedtoinitializeskin中文提示无法初始化界面的错误。这说明你的电脑安装了双显卡,而edius所使用的是图形显卡。可以选择edius图标右键...
- Flash Player模拟器更新:Rufffle(flash模拟器安卓下载高版本)
-
Ruffle是一个适用于WindowsPC的FlashPlayer模拟器,用Rust编写。Ruffle作为一个独立的应用程序在所有现代操作系统上原生运行,并通过使用WebAssembly在所有现代...
- 支持终身免费4G流量,星星充电7kW星际智能交流充电桩拆解
-
前言近期星星充电推出了一款星际智能交流充电桩,在正面设有灯条,可根据灯条颜色和显示直观了解充电状态,并设有屏幕显示充电状态和ui表情。充电桩支持220V/7kW充电功率,适配主流新能源车型。并支持终身...
- 乐动随心之fancy pop(乐动随心壶多少钱一个)
-
跳动飞扬的音符像是连通人与人之间心电感应的通关密码,融化陌生,拉近彼此。此次我们邀请到宅男女神江语晨,化身音乐精灵。在歌手、演员身份间游刃自如的她,为我们生动诠释了三种不同的音乐时尚风格,娴静可爱,灵...
- Asus Zenflash 手机也能玩引闪,从此相机是路人
-
在讲解Zenflash之前,不得不提索爱的K750c,这个机器采用了氙气闪光灯,让手机的拍摄上了档次,可玩性更高,不过,说实话,当时手机的摄像头像素低,成像一般,没有掀起太大的波澜,可现在,手机的Cm...
- Axure有哪些鲜为人知的使用技巧?(axure的使用教程)
-
阿拓带你飞:不管是想入门产品经理还是已经是PM的人对AXURE都很关注,它是制作产品原型的重要工具,但是有多少人了解AXURE的使用技巧?本文是来自“知乎问答”整理的回答,一起来看看那些不常用的使用技...
- 挑战黑夜 华硕ZenFlash氙气闪光灯评测
-
【机锋配件】说到摄影,相信许多朋友都非常喜欢,不管是外出游玩拍拍风景,还是和朋友之间聚会,都会掏出手机拍两张,在餐前拍照晒朋友圈更是成为了许多用户的日常爱好,就算不是专业的摄影爱好者,大家也都有一颗热...
- WPS 演示倒计时 3 步设置!从数字动画到进度条全场景教程
-
做PPT时想添加倒计时却找不到入口?WPS演示自带的"动画+计时"功能就能轻松实现——无论是课堂互动的30秒答题倒计时、商务汇报的5分钟限时讲解,还是活动暖场的动...
- flash动画an制作MG动画元素如何调节透明度,小白...
-
如何在flash动画软件里面调节mg动画元素的透明?因为flash动画软件现在已经升级为flash动画软件,所以直接用新版flash动画软件开工,基本功能都差不多,只是flash增加很多智能化、人性...