java - How to allow all and any requests with Spring Security?
问题描述
I've just added Spring Security to my project. I've also added this configuration:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().permitAll();
}
}
but now not all of my endpoints work. In fact only a single endpoint works, for the rest I get 403 Forbidden
. What could be the problem? How can I allow any and all requests (effectively making security a pass-through).
解决方案
如果您想允许某些 URL 无需身份验证即可访问,最好准备一些白名单并将其传递给 antMatchers。antMathers 也接受外卡。如果您肯定不希望对任何端点进行身份验证,请将 /**. 但是你已经有了 spring security 为什么不使用它的全部功能。这是一个简单的方法。
private static final String[] AUTH_WHITELIST = {
"/v2/api-docs", "/swagger-resources", "/swagger-resources/**",
};
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests()
.antMatchers(AUTH_WHITELIST).permitAll()
.antMatchers("/csrf").permitAll()
.anyRequest().authenticated();
}