当前位置:首页 > 技术分析 > 正文内容

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

ruisui884个月前 (03-09)技术分析18

前言

使用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 findTokensByClientIdAndUserName(String clientId, String userName);
 
  /**
   * @param clientId the client id to search
   * @return a collection of access tokens
   */
  Collection 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种实现方式,在实际工作中可以按照具体情况进行调整。


以上为全部内容。

扫描二维码推送至手机访问。

版权声明:本文由ruisui88发布,如需转载请注明出处。

本文链接:http://www.ruisui88.com/post/2622.html

分享给朋友:

“详解springSecurity之令牌存储TokenStore实现的4种方式” 的相关文章

企业费用管控遇难题,财务经理上线费控报销系统,老板直呼加薪

如何向浪费开刀?这几乎是当前很多企业要面临的一个关键性问题,企业近年的经营都遇到很大的难题,虽然销售额在上升,但是费用也在上升,给企业带来很大的压力。费用管控对企业而言就显得格外重要。那么财务人员如何做好费用管控?公司的费用支出总的来说包括两方面吧:差旅费用和日常费用、这其中差旅费用又是一项比较大的...

双子座应用程序推出模型切换器以在Android上访问2.0

#头条精品计划# 快速导读谷歌推出了Gemini 2.0 Flash实验版,现已在其安卓应用中可用,之前仅在gemini.google.com网站上提供。新版本的15.50包含模型切换器,用户可以在设置中选择不同模型,包括1.5 Pro、1.5 Flash和2.0 Flash实验版。谷歌提醒,2.0...

深度解析!AI智能体在To B领域应用,汽车售后服务落地全攻略

在汽车售后服务领域,AI智能体的应用正带来一场效率和专业度的革命。本文深度解析了一个AI智能体在To B领域的实际应用案例,介绍了AI智能体如何通过提升服务顾问和维修技师的专业度及维修效率,优化汽车售后服务流程。上周我分享了AI智能体+AI小程序To C的AI应用场景《1000%增长!我仅用一个小时...

虚幻引擎5.5现已发布 手游开发、动画制作重大改进

Epic在今天发布了虚幻引擎5.5,现可通过Epic Launcher下载。此版本在动画创作、渲染、虚拟制片、移动端游戏开发和开发人员迭代工具集等方面做出了重大改进。 官方博客:虚幻引擎5.5现已发布,在动画创作、虚拟制作和移动游戏开发方面取得了显著进步,渲染、摄像机内视觉特效和开发人员迭代等领域的...

Python中的11 种数组算法

1. 创建数组 创建数组意味着留出一个连续的内存块来存储相同类型的元素。在大多数语言中,您可以在创建数组时指定数组的大小。假设您正在书架上整理一组书籍,并且您需要为正好 10 本书预留空间。功能架上的每个空间都对应于数组中的一个索引。# Example in Python arr = [1, 2,...

Vue学习笔记之动态路由的参数传递应用及技巧

路由的参数传递:①通过params的类型· 配置路由格式:/router/:id· 传递的方式:在path后面跟上对应的值· 传递后形成的路径:/router/list,/router/profile这个就是前两篇中提到的"动态路由"中有应用过这个方法:②通过query的类型(对象方...