如何使用 Spring Security 允许所有请求?

Ada*_*old 11 java spring spring-security

我刚刚将 Spring Security 添加到我的项目中。我还添加了这个配置:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().permitAll();
    }

}
Run Code Online (Sandbox Code Playgroud)

但现在并非我的所有端点都有效。事实上,只有一个端点有效,其余的我都得到了403 Forbidden。可能是什么问题呢?我怎样才能允许任何和所有请求(有效地使安全性成为传递)。

Jan*_*oCG 11

我必须添加.csrf().disable()才能使其正常工作。

所以对我来说整个解决方案是

http.csrf().disable().authorizeRequests().anyRequest().permitAll();
Run Code Online (Sandbox Code Playgroud)


小智 7

如果您想允许某些 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(); 
}
Run Code Online (Sandbox Code Playgroud)