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...拿去用了, 于是注释掉, 终于登上去了, 效果和原来项目一样了, 长吁一口气。

 

猜你喜欢

转载自www.cnblogs.com/sunsay/p/12984163.html