Hab*_*chi 5 java spring spring-security jwt spring-boot
我正在开发一个 Spring Boot 应用程序,在其中我定义了要执行的过滤器来管理获取和验证令牌。因此,在我的 Web 安全类配置中,我设法做到了这一点:
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
// we don't need CSRF because our token is invulnerable
.csrf().disable()
// don't create session
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
// .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
// allow anonymous resource requests
.antMatchers(HttpMethod.GET, "/", "/*.html", "/favicon.ico", "/**/*.html", "/**/*.css", "/**/*.js").permitAll()
.antMatchers("/auth/**").permitAll()
.antMatchers("/places/public").permitAll()
.anyRequest().authenticated();
// Custom JWT based security filter
httpSecurity.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
// disable page caching
httpSecurity.headers().cacheControl();
}
Run Code Online (Sandbox Code Playgroud)
authenticationTokenFilterBean 是一个用 @Bean 注释的方法,它返回我的过滤器的实例:
public class JwtFilter extends OncePerRequestFilter{
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private JwtService jwtService;
@Value("${jwt.header}")
private String authorizationHeader;
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
String token = httpServletRequest.getHeader(authorizationHeader);
String username = jwtService.getUsernameFromToken(token);
if(username!=null && SecurityContextHolder.getContext().getAuthentication() ==null){
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
if(jwtService.isTokenValid(token, userDetails)){
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
}
}
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
}
Run Code Online (Sandbox Code Playgroud)
由于我扩展了 OncePerRequestFilter,因此每个请求仅调用该过滤器一次,而 GenericFilter 的情况则不同,GenericFilter 需要由 servlet 执行一次,而 Spring 安全性则需要执行一次。
我遇到的问题是,即使我使用 PermitAll() 方法允许它们,我的配置类中描述的 ant 匹配器也会被过滤器拦截,我尝试从 WebSecurityConfigurerAdapter 重写 configure(WebSecurity web) 方法并忽略它们,但仍然没用。
如何配置 Spring security 来跳过这些请求的过滤器?我已经检查过这个问题Spring Security JWT Filter 适用于所有请求,但没有解决方案。
谢谢
Dav*_*ral -1
我是这样避免这个问题的,大家可以参考一下:
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain filterChain) throws ServletException, IOException {
if("/login".equals(req.getServletPath()) && "POST".equalsIgnoreCase(req.getMethod())){
// ......
}
filterChain.doFilter(req, res);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2218 次 |
| 最近记录: |