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

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

ruisui882个月前 (03-09)技术分析10

前言

使用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种方式” 的相关文章

快速掌握 Git:程序员必会的版本控制技巧

在现代软件开发中,版本控制系统(VCS)是开发人员不可或缺的工具。无论是个人项目,还是多人协作的团队开发,良好的版本控制都能确保代码管理的高效性与稳定性。而在版本控制系统中,Git 凭借其分布式、灵活性和高效性,成为了最流行的工具之一。几乎所有的开发团队都在使用 Git 来管理代码版本、协作开发和追...

jvm疯狂吃内存,到底是谁的锅?

jvm应该是每一个java程序员都需要掌握的内容,但是在没有遇到问题之前,很多都是基于理论的,唯有实战才能增加个人的知识储备。本文是从一个角度来分析是谁在狂吃内存,希望对你有所帮助。本文是易观技术人员注意到一台开发机上各个微服务进程占用内存很高,随即便展开了调查......ps:本文来源于:http...

22《Vue 入门教程》VueRouter 路由嵌套

1. 前言本小节我们介绍如何嵌套使用 VueRouter。嵌套路由在日常的开发中非常常见,如何定义和使用嵌套路由是本节的重点。同学们在学完本节课程之后需要自己多尝试配置路由。2. 配置嵌套路由实际项目中的应用界面,通常由多层嵌套的组件组合而成。同样地,URL 中各段动态路径也按某种结构对应嵌套的各层...

「干货」Vue+Element前端导入导出Excel

作者:xrkffgg转发链接:https://segmentfault.com/a/11900000189936191 前言1.1 业务场景由前台导入Excel表格,获取批量数据。根据一个数组导出Excel表格。2 实现原理2.1 引入工具库file-saver、xlsx、script-loader...

三勾知识付费(PHP+vue3)微信小程序平台+SAAS+前后端源码

项目介绍三勾小程序商城基于thinkphp8+element-plus+uniapp打造的面向开发的小程序商城,方便二次开发或直接使用,可发布到多端,包括微信小程序、微信公众号、QQ小程序、支付宝小程序、字节跳动小程序、百度小程序、android端、ios端。软件架构后端:thinkphp8 管理端...

html5迁移到微信小程序的 方法 亲测可用

切图网习惯于在做小程序之前先做成html5+vuejs的形式,因为html5切图是我们比较熟悉的方式,而且有专业的工具 以及浏览器调试也会更加的方便 灵活,效率高,而且html5的方式可以方便预览看效果,方便调整,当html5页面做好确认没问题以后 再转成小程序或者官方出品wepy的方式,这个时候就...