springsecurity自定义jwt过滤器
时间: 2025-03-07 07:02:42 浏览: 31
### 创建和配置自定义JWT认证过滤器
在Spring Security中创建和配置自定义JWT认证过滤器涉及多个方面的工作,包括但不限于编写具体的过滤器逻辑以及将其适当地集成到安全配置之中。
#### 编写自定义JWT认证过滤器类
为了实现一个能够处理JWT令牌验证的过滤器,通常会继承`OncePerRequestFilter`并重载其doFilterInternal方法,在该方法内部完成对请求头中的Authorization字段解析、Token有效性校验等工作。如果Token有效,则构建相应的`Authentication`对象,并调用`SecurityContextHolder.getContext().setAuthentication(authentication)`设置当前线程的安全上下文[^2]。
```java
public class JwtAuthTokenFilter extends OncePerRequestFilter {
@Autowired
private JwtProvider tokenProvider;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
try {
String jwt = getJwt(request);
if (jwt != null && tokenProvider.validateJwtToken(jwt)) {
Claims claims = tokenProvider.getClaimsFromJwtToken(jwt);
DefaultOAuth2User authentication = new DefaultOAuth2User(
Collections.emptyList(),
claims,
"sub"
);
UsernamePasswordAuthenticationToken authToken =
new UsernamePasswordAuthenticationToken(authentication, null, authentication.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authToken);
}
} catch (Exception e) {
logger.error("Cannot set user authentication: {}", e.getMessage());
}
filterChain.doFilter(request, response);
}
private String getJwt(HttpServletRequest request) {
String authHeader = request.getHeader("Authorization");
if (authHeader != null && authHeader.startsWith("Bearer ")) {
return authHeader.replace("Bearer ", "");
}
return null;
}
}
```
此代码片段展示了如何从HTTP头部提取JWT字符串,并利用`tokenProvider`工具类来进行解码与验证操作;一旦确认Token合法即刻更新当前用户的认证状态[^3]。
#### 配置Spring Security以应用自定义过滤器
为了让上述编写的过滤器生效,还需要调整应用程序内的Spring Security配置文件或Java Config类,确保新的过滤器被正确加载至过滤链当中。这一步骤可以通过覆写WebSecurityConfigurerAdapter下的configure(HttpSecurity http)方法来达成目的:
```java
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public JwtAuthTokenFilter authenticationJwtTokenFilter() {
return new JwtAuthTokenFilter();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable().
authorizeRequests()
.antMatchers("/api/auth/**").permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
http.headers().frameOptions().sameOrigin(); // H2 Console Support
}
...
}
```
在此处不仅指定了哪些路径允许匿名访问(`/api/auth/**`),还特别强调了整个API应处于无状态模式下运行(通过设定Session Creation Policy),从而更好地契合RESTful API设计原则及JWT机制特点[^1]。
阅读全文
相关推荐


















