百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

详解springSecurity之令牌存储TokenStore实现的4种方式

haoteby 2025-06-23 19:10 17 浏览

前言

使用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种,分别是:

  1. InMemoryTokenStore(保存本地内存)
  2. JdbcTokenStore(保存到数据库)
  3. JwkTokenStore(全部信息返回到客户端
  4. 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种实现方式,在实际工作中可以按照具体情况进行调整。


以上为全部内容。

相关推荐

一日一技:用Python程序将十进制转换为二进制

用Python程序将十进制转换为二进制通过将数字连续除以2并以相反顺序打印其余部分,将十进制数转换为二进制。在下面的程序中,我们将学习使用递归函数将十进制数转换为二进制数,代码如下:...

十进制转化成二进制你会吗?#数学思维

六年级奥赛起跑线:抽屉原理揭秘。同学们好,我是你们的奥耀老师。今天一起来学习奥赛起跑线第三讲二进制计数法。例一:把十进制五十三化成二进制数是多少?首先十进制就是满十进一,二进制就是满二进一。二进制每个...

二进制、十进制、八进制和十六进制,它们之间是如何转换的?

在学习进制时总会遇到多种进制转换的时候,学会它们之间的转换方法也是必须的,这里分享一下几种进制之间转换的方法,也分享两个好用的转换工具,使用它们能够大幅度的提升你的办公和学习效率,感兴趣的小伙伴记得点...

c语言-2进制转10进制_c语言 二进制转十进制

#include<stdio.h>intmain(){charch;inta=0;...

二进制、八进制、十进制和十六进制数制转换

一、数制1、什么是数制数制是计数进位的简称。也就是由低位向高位进位计数的方法。2、常用数制计算机中常用的数制有二进制、八进制、十进制和十六进制。...

二进制、十进制、八进制、十六进制间的相互转换函数

二进制、十进制、八进制、十六进制间的相互转换函数1、输入任意一个十进制的整数,将其分别转换为二进制、八进制、十六进制。2、程序代码如下:#include<iostream>usingna...

二进制、八进制、十进制和十六进制等常用数制及其相互转换

从大学开始系统的接触计算机专业,到现在已经过去十几年了,今天整理一下基础的进制转换,希望给还在上高中的表妹一个入门的引导,早日熟悉这个行业。一、二进制、八进制、十进制和十六进制是如何定义的?二进制是B...

二进制如何转换成十进制?_二进制如何转换成十进制例子图解

随着社会的发展,电器维修由继电器时代逐渐被PLC,变频器,触摸屏等工控时代所替代,特别是plc编程,其数据逻辑往往涉及到数制二进制,那么二进制到底是什么呢?它和十进制又有什么区别和联系呢?下面和朋友们...

二进制与十进制的相互转换_二进制和十进制之间转换

很多同学在刚开始接触计算机语言的时候,都会了解计算机的世界里面大多都是二进制来表达现实世界的任何事物的。当然现实世界的事务有很多很多,就拿最简单的数字,我们经常看到的数字大多都是十进制的形式,例如:我...

十进制如何转换为二进制,二进制如何转换为十进制

用十进制除以2,除的断的,商用0表示;除不断的,商用1表示余0时结束假如十进制用X表示,用十进制除以2,即x/2除以2后为整数的(除的断的),商用0表示;除以2除不断的,商用1表示除完后的商0或1...

十进制数如何转换为二进制数_十进制数如何转换为二进制数举例说明

我们经常听到十进制数和二进制数,电脑中也经常使用二进制数来进行计算,但是很多人却不清楚十进制数和二进制数是怎样进行转换的,下面就来看看,十进制数转换为二进制数的方法。正整数转二进制...

二进制转化为十进制,你会做吗?一起来试试吧

今天孩子问把二进制表示的110101改写成十进制数怎么做呀?,“二进制”简单来说就是“满二进一”,只用0和1共两个数字表示,同理我们平常接触到的“十进制”是“满十进一”,只用0-9共十个数字表示。如果...

Mac终于能正常打游戏了!苹果正逐渐淘汰Rosetta转译

Mac玩家苦转译久矣!WWDC2025苹果正式宣判Rosetta死刑,原生游戏时代终于杀到。Metal4光追和AI插帧技术直接掀桌,连Steam都连夜扛着ARM架构投诚了。看到《赛博朋克2077》...

怎么把视频的声音提出来转为音频?音频提取,11款工具实测搞定

想把视频里的声音单独保存为音频文件(MP3/AAC/WAV/FLAC)用于配音、播客、听课或二次剪辑?本文挑出10款常用工具,给出实测可复现的操作步骤、优缺点和场景推荐。1)转换猫mp3转换器(操作门...

6个mp4格式转换器测评:转换速度与质量并存!

MP4视频格式具有兼容性强、视频画质高清、文件体积较小、支持多种编码等特点,适用于网络媒体传播。如果大家想要将非MP4格式的视频转换成MP4的视频格式的话,可以使用MP4格式转换器更换格式。本文分别从...