提交 dd5e92b6 编写于 作者: H hxr

refactor: RedisTemplate 通过构造函数注入到JwtTokenFilter

上级 29f2413d
......@@ -8,6 +8,7 @@ import com.youlai.system.filter.VerifyCodeFilter;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
......@@ -35,6 +36,7 @@ public class SecurityConfig {
private final MyAuthenticationEntryPoint authenticationEntryPoint;
private final MyAccessDeniedHandler accessDeniedHandler;
private final RedisTemplate<String, Object> redisTemplate;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
......@@ -56,7 +58,7 @@ public class SecurityConfig {
// 验证码校验过滤器
http.addFilterBefore(new VerifyCodeFilter(), UsernamePasswordAuthenticationFilter.class);
// JWT 校验过滤器
http.addFilterBefore(new JwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
http.addFilterBefore(new JwtTokenFilter(redisTemplate), UsernamePasswordAuthenticationFilter.class);
return http.build();
}
......
......@@ -31,6 +31,12 @@ import java.util.Map;
*/
public class JwtTokenFilter extends OncePerRequestFilter {
private final RedisTemplate<String, Object> redisTemplate;
public JwtTokenFilter(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
/**
* 从请求中获取 JWT Token,校验 JWT Token 是否合法
* <p>
......@@ -43,11 +49,10 @@ public class JwtTokenFilter extends OncePerRequestFilter {
try {
if (StrUtil.isNotBlank(token)) {
Map<String, Object> payload = JwtUtils.parseToken(token);
String jti = Convert.toStr(payload.get(JWTPayload.JWT_ID));
RedisTemplate redisTemplate = SpringUtil.getBean("redisTemplate", RedisTemplate.class);
Boolean isBlack = redisTemplate.hasKey(CacheConstants.BLACKLIST_TOKEN_PREFIX + jti);
if (isBlack) {
String jti = Convert.toStr(payload.get(JWTPayload.JWT_ID));
Boolean isTokenBlacklisted = redisTemplate.hasKey(CacheConstants.BLACKLIST_TOKEN_PREFIX + jti);
if (isTokenBlacklisted ) {
ResponseUtils.writeErrMsg(response, ResultCode.TOKEN_INVALID);
return;
}
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册