如何在Spring Security中使用过滤器检查 token 是否过期
时间: 2024-05-12 16:14:09 浏览: 337
在Spring Security中,可以使用过滤器来检查token是否过期。具体实现步骤如下:
1. 创建一个继承自`OncePerRequestFilter`的过滤器,用于检查token是否过期:
```java
public class JwtTokenAuthenticationFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
String token = extractToken(request);
// 检查token是否过期,如果过期则返回错误信息
if (isTokenExpired(token)) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token has expired");
return;
}
chain.doFilter(request, response);
}
private boolean isTokenExpired(String token) {
// 解析token获取过期时间
Date expiration = getExpirationDateFromToken(token);
// 检查当前时间是否晚于过期时间
return expiration.before(new Date());
}
private String extractToken(HttpServletRequest request) {
// 从请求头或请求参数中获取token
String bearerToken = request.getHeader("Authorization");
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
return bearerToken.substring(7);
}
return request.getParameter("token");
}
private Date getExpirationDateFromToken(String token) {
// 解析token获取过期时间
return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody().getExpiration();
}
}
```
2. 在Spring Security配置中将该过滤器添加到过滤器链中:
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtTokenAuthenticationFilter jwtTokenAuthenticationFilter;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/api/authenticate").permitAll()
.anyRequest().authenticated()
.and()
.addFilterBefore(jwtTokenAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
}
}
```
这样,当请求经过该过滤器时,将会检查token是否过期,并在token过期时返回错误信息。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)