簡體   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