@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/**
)。使用postman测试时
localhost/test
即使我有 antMatchers("/test").permitAll()
它仍然通过过滤器.如何绕过过滤器?
最佳答案
您可以禁用某些 URL 的 Spring Security 过滤器链,请参阅 WebSecurity#ignoring
:
Allows adding
RequestMatcher
instances that should that Spring Security should ignore. Web Security provided by Spring Security (including theSecurityContext
) will not be available onHttpServletRequest
that match. Typically the requests that are registered should be that of only static resources. For requests that are dynamic, consider mapping the request to allow all users instead.Example Usage:
webSecurityBuilder.ignoring() // ignore all URLs that start with /resources/ or /static/ .antMatchers("/resources/**", "/static/**");
因此,您可以覆盖
WebSecurityConfigurerAdapter#configure
:Override this method to configure
WebSecurity
. For example, if you wish to ignore certain requests.
忽略路径
/test
您必须在配置中添加以下方法:public void configure(WebSecurity web)
webSecurityBuilder
.ignoring()
.antMatchers("/test");
}
关于spring-security - Spring Security 在自定义过滤器上排除 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40475620/