Spring Boot security 默認攔截靜態資源的解決方法

Spring Boot security 會默認登陸之前攔截全部css, js,img等動態資源,導致我們的公開主頁在登陸之前很醜陋

像這樣:

網上很多解決辦法都過時瞭比如還在使用WebSecurityConfigurerAdapte,antMatchers

public class SecurityConfigurer extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(WebSecurity web) throws Exception {
    web
        .ignoring()
        .antMatchers("/resources/**");
}
}

WebSecurityConfigurerAdapter和antMatchers已經被Spring Security 6.0棄用,現最新的是使用securityFilterChain class 如下圖:

public class WebSecurityConfig {
 
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests((requests) -> requests
                .requestMatchers("/", "/home").permitAll()
                .anyRequest().authenticated()
            )
            .formLogin((form) -> form
                .loginPage("/login")
                .permitAll()
            )
            .logout((logout) -> logout.permitAll());
 
        return http.build();
    }
}

這裡隻需要添加.requestMatchers("/resources/**").permitAll()就可以允許訪問resources文件下資源

註意.antMatchers 已經棄用,用.requestMatchers代替

 public class WebSecurityConfig {
 
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests((requests) -> requests
                .requestMatchers("/", "/home").permitAll()
                 //放行靜態資源
                .requestMatchers("/resources/**").permitAll()
                .anyRequest().authenticated()
            )
            .formLogin((form) -> form
                .loginPage("/login")
                .permitAll()
            )
            .logout((logout) -> logout.permitAll());
 
        return http.build();
    }
}

但是我看網上沒有人解釋需要註意這裡“/resources/**"並不一定萬能,具體鏈接得根據你插入css/js的路徑來比如這裡使用assets/**

那麼你securityFilterChain class裡就得是.requestMatchers("/assets/**").permitAll()

之後再運行,成功!

到此這篇關於Spring Boot security 默認攔截靜態資源的文章就介紹到這瞭,更多相關Spring Boot security攔截靜態資源內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: