Spring Security配置類, 啟動后報Can't configure antMatchers after anyRequest...


原來的同事丟過來一個模塊工程, 讓我幫忙改Spring Boot, 搗鼓半天整完了, 就剩權限了。想着一大堆配置類, 單留着Spring Security的xml似乎不大和諧, 正好對Spring Security不熟, 索性練練手。

結果一個小時, 被Spring Security整的死去活來。之前一個交友的項目, 權限不是我做的, 以為能拿來借鑒借鑒。但翻出來看了下, 是用JWT做攔截, 只用SpringSecurity做鹽加密。而現在手上這個項目原來的username和password是在spring security里配置的, 看來只能照着原來項目的xml配置改。

開始配了半天, 一直報一個Can't configure antMatchers after anyRequest...的錯誤, 上StackOverflow看了以下別人的, 照着代碼調整了下, 還是沒有解決。然后想難道是super.configure(http)里搞的鬼, 點進去看了下, 結果還真是, 就趕緊去掉了。子類重寫方法時, 如果用不到父類的方法, 一定要去掉自動生成的super。

終於配好了, 如下:

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

   @Override
   protected void configure(HttpSecurity http) throws Exception {
        //authorizeRequests表示開始說明需要的權限
      http.httpBasic()
                  .and()
              .formLogin().loginPage("/login.html")
          .defaultSuccessUrl("/admin/index.html")
              .loginProcessingUrl("/login").failureUrl("/error.html")
                  .and()
              .logout().logoutSuccessUrl("/login.html")
                  .and()
              .authorizeRequests()
              .antMatchers("/login.html").permitAll()
              .antMatchers("/error.html").permitAll()
              .antMatchers("/css/**").permitAll()
              .antMatchers("/js/**").permitAll()
              .antMatchers("/img/**").permitAll()
              .antMatchers("/plugins/**").permitAll()
                  .and()
              .authorizeRequests()
              .antMatchers("/**").hasRole("USER")
              .anyRequest().authenticated()
              .and().csrf().disable();
       
       http.headers().frameOptions().sameOrigin();
  }

}

application.yml里也加上了

spring.
security:
  user:
    name: admin
    password: 123456
    roles: USER

結果, 怎么都登不進去, 一直報用戶名密碼錯誤, 網上搜了, 沒發現類似問題。

沒辦法, 估摸可能是我剛才照着Token Auth的方式注入了BCryptPasswordEncoder, 被ConditionalOn...拿去用了, 於是注釋掉, 終於登上去了, 效果和原來項目一樣了, 長吁一口氣。

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM