@SuppressWarnings("SpringJavaAutowiringInspection")
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;
@Autowired
private UserDetailsService userDetailsService;
@Autowired
public void configureAuthentication(AuthenticationManagerBuilder
authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder.userDetailsService(userDetailsService);
}
@Bean
public JwtAuthenticationTokenFilter authenticationTokenFilterBean() throws Exception {
return new JwtAuthenticationTokenFilter();
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.csrf().disable()
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/test").permitAll()
.antMatchers("/api/**").permitAll()
.anyRequest().authenticated();
httpSecurity.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
}
}
我有一个在Spring Security之前运行的自定义过滤器。我希望能够从过滤器和Spring Security中排除某些URL(如/test
)以及其他要拦截的URL(如/api/**
)。
使用邮递员测试localhost/test
时,即使我有antMatchers("/test").permitAll()
,它仍会通过过滤器。
如何绕过过滤器?
答案 0 :(得分:5)
您可以为某些网址停用Spring Security过滤器链,请参阅WebSecurity#ignoring
:
允许添加Spring Security应忽略的
RequestMatcher
个实例。 Spring Security提供的Web安全性(包括SecurityContext
)将不会在匹配的HttpServletRequest
上提供。通常,注册的请求应该只是静态资源的请求。对于动态请求,请考虑将请求映射为允许所有用户。示例用法:
webSecurityBuilder.ignoring() // ignore all URLs that start with /resources/ or /static/ .antMatchers("/resources/**", "/static/**");
因此,您可以覆盖WebSecurityConfigurerAdapter#configure:
重写此方法以配置
WebSecurity
。例如,如果您希望忽略某些请求。