一、环境准备
【Spring Security Oauth2】构建授权服务器(一):内存模式
二、构建授权服务器(二):Jwt模式
1、改造AuthorizationServer类
- 引入新依赖注入
@Autowired private JwtAccessTokenConverter accessTokenConverter;
- 修改tokenService()方法
/**
* 令牌服务
*
* @return
*/
@SuppressWarnings({"All"})
@Bean
public AuthorizationServerTokenServices tokenService() {
DefaultTokenServices service = new DefaultTokenServices();
// 客户端信息服务
service.setClientDetailsService(clientDetailsService);
// 是否刷新令牌
service.setSupportRefreshToken(true);
// 令牌存储策略
service.setTokenStore(tokenStore);
// 令牌默认有效期2小时
service.setAccessTokenValiditySeconds(7200);
// 刷新令牌默认有效期3天
service.setRefreshTokenValiditySeconds(259200);
// 加入JWT配置(新添加的配置)
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
tokenEnhancerChain.setTokenEnhancers(Arrays.asList(accessTokenConverter));
service.setTokenEnhancer(tokenEnhancerChain);
return service;
}
2、改造TokenConfig类
- TokenConfig类信息
package com.cyun.security.oauth2.config;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
/**
* 自定义 TokenConfig 配置
*
* @author He PanFu
* @date 2021-12-19 17:55:23
*/
@Configuration
@RequiredArgsConstructor
public class TokenConfig {
private String SIGNING_KEY = "uaa123";
/**
* 使用Jwt
* @return
*/
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
// 对称秘钥,资源服务器使用该秘钥来验证
converter.setSigningKey(SIGNING_KEY);
return converter;
}
/**
* token 保存
*
* @return
*/
@Bean
public TokenStore tokenStore() {
// 使用Jwt
return new JwtTokenStore(accessTokenConverter());
// 使用内存模式
// return new InMemoryTokenStore();
}
}