繁体   English   中英

如何使用 Spring 安全性允许所有和任何请求?

[英]How to allow all and any requests with Spring Security?

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

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

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

}

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

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

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

http.csrf().disable().authorizeRequests().anyRequest().permitAll();

如果您想允许某些 URL 无需身份验证即可访问,最好准备一些白名单并将其传递给方法antMatchers()

antMathers()也接受通配符 如果您肯定不希望对任何端点进行身份验证,请放置/** 但是您已经拥有 Spring 安全性,为什么不使用它的全部功能。

这是一个简单的方法。

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(); 
}

你可以试试

http.authorizeRequests().antMatchers("/**").permitAll();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM