Spring oauth2.0 刷新token后设置原token5分钟内继续可用

默认情况下刷新token后原token会立马不可用。但是在某些情况下我们需要刷新token后原token在一定时间内继续可用(例如微信的刷新token)。

通过查看DefaultTokenServices中的刷新token方法refreshAccessToken可以看到生成新的token后会调用removeAccessTokenUsingRefreshToken方法,此方法默认会删除存储的相关token信息

private void removeAccessTokenUsingRefreshToken(String refreshToken) {
		byte[] key = serializeKey(REFRESH_TO_ACCESS + refreshToken);
		List<Object> results = null;
		RedisConnection conn = getConnection();
		try {
			conn.openPipeline();
			conn.get(key);
			conn.del(key);
			results = conn.closePipeline();
		} finally {
			conn.close();
		}
		if (results == null) {
			return;
		}
		byte[] bytes = (byte[]) results.get(0);
		String accessToken = deserializeString(bytes);
		if (accessToken != null) {
			removeAccessToken(accessToken);
		}
	}

所以就需要重写该方法设置不立即删除

 

首先需要自定义tokenStore

public class OAuth2AuthorizationConfiguration extends AuthorizationServerConfigurerAdapter {
    @Override
	public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
		endpoints.accessTokenConverter(new FrameworkAccessTokenConverter());
		endpoints.authorizationCodeServices(meiceAuthorizationCodeService)
				.tokenEnhancer(jwtAccessTokenConverter())
				.reuseRefreshTokens(false)
                // 使用自定义tokenStore管理tongken
				.tokenStore(meiceTokenStore)
				.userDetailsService(meiceUserDetailsService)
				.authenticationManager(authenticationManager)
				.setClientDetailsService(meiceClientDetailsService);
		endpoints.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
		endpoints.exceptionTranslator(new MeiceWebResponseExceptionTranslator());
		//使用自定义granter以返回refresh_token.(默认granter不返回)
		endpoints.tokenGranter(new CompositeTokenGranter(getMeiceTokenGranters()));
	}
}
//自定义tokenStore(其他代码参考org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore)
public class IRedisTokenStore implements TokenStore {
    @Override
	public void removeAccessTokenUsingRefreshToken(OAuth2RefreshToken refreshToken) {
		removeAccessTokenUsingRefreshToken(refreshToken.getValue());
	}

	private void removeAccessTokenUsingRefreshToken(String refreshToken) {
		String token = (String) this.redisTemplate.opsForValue().get(REFRESH_TO_ACCESS + refreshToken);

		if (token != null) {
			//设置刷新后5分钟内继续可用
			redisTemplate.expire(ACCESS + token, 300, TimeUnit.SECONDS);
		}
	}
}

至此Token将在刷新后5分钟过期删除.

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,你想了解如何在Spring Boot中整合Spring Security和OAuth 2.0来实现token认证。下面是一个基本的步骤: 1. 添加依赖:在你的`pom.xml`文件中添加Spring Security和OAuth 2.0的依赖。 ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-client</artifactId> </dependency> ``` 2. 配置Spring Security:创建一个继承自`WebSecurityConfigurerAdapter`的配置类,并覆盖`configure`方法,配置Spring Security。 ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/oauth2/**", "/login/**", "/logout/**") .permitAll() .anyRequest() .authenticated() .and() .oauth2Login() .loginPage("/login") .and() .logout() .logoutUrl("/logout") .logoutSuccessUrl("/") .deleteCookies("JSESSIONID"); } } ``` 这个配置类指定了哪些URL需要进行认证,`antMatchers`方法指定了不需要认证的URL。 3. 配置OAuth 2.0客户端:创建一个继承自`WebSecurityConfigurerAdapter`的配置类,并使用`@EnableOAuth2Client`注解开启OAuth 2.0客户端。 ```java @Configuration @EnableOAuth2Client public class OAuth2ClientConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { // 配置HTTP Security } @Bean public OAuth2AuthorizedClientService authorizedClientService( OAuth2ClientRegistrationRepository clientRegistrationRepository) { return new InMemoryOAuth2AuthorizedClientService(clientRegistrationRepository); } } ``` 这个配置类可以用来配置OAuth 2.0的客户端,你可以在`configure`方法中添加一些额外的配置。 4. 配置OAuth 2.0客户端注册:在`application.properties`文件中配置OAuth 2.0的客户端注册信息。 ```properties spring.security.oauth2.client.registration.my-client-id.client-id=your-client-id spring.security.oauth2.client.registration.my-client-id.client-secret=your-client-secret spring.security.oauth2.client.registration.my-client-id.scope=your-scopes spring.security.oauth2.client.registration.my-client-id.authorization-grant-type=authorization_code spring.security.oauth2.client.registration.my-client-id.redirect-uri=your-redirect-uri ``` 这个配置文件中的`my-client-id`是你自己指定的客户端ID,你需要将其替换为你自己的信息。 这些步骤是实现Spring Boot中整合Spring Security和OAuth 2.0实现token认证的基本步骤。你可以根据自己的需求进行进一步的配置和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值