为什么Spring无法使用BasicAuth识别我的WebSecurityConfigurerAdapter?

时间:2019-01-18 13:21:18

标签: spring-security

我有一个要使用BasicAuth的Maven模块项目。我所有的业务和控制器都作为依赖项导入。在我的“主要”项目中,我有App.java类:

@SpringBootApplication(scanBasePackages = { "controller", "service" })
@EnableAutoConfiguration
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

在同一目录下

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

static final String adminRole = "ADMIN";
static final String standardRole = "STANDARD";

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication()
      .withUser("user").password("{noop}pass").roles(standardRole)
      .and()
      .withUser("admin").password("{noop}admin").roles(adminRole, standardRole);
}

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  static final String adminRole = "ADMIN";
  static final String standardRole = "STANDARD";

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication()
      .withUser("user").password("{noop}pass").roles(standardRole)
      .and()
      .withUser("admin").password("{noop}admin").roles(adminRole, standardRole);
  }

  @Override
  public void configure(HttpSecurity http) throws Exception {
    http
      .authorizeRequests()
            .antMatchers("/seriousInfo").hasRole(adminRole)
            .anyRequest().authenticated()
          .and().httpBasic();
  }

}

是否需要application.yml上的其他信息?即使执行此操作,我也会获得带有一些随机生成的密码的日志

1 个答案:

答案 0 :(得分:1)

添加@EnableWebSecurity批注。那么您可以删除@Configuration,因为@EnableWebSecurity

正在调用它

https://docs.spring.io/spring-security/site/docs/5.1.3.RELEASE/api/org/springframework/security/config/annotation/web/configuration/EnableWebSecurity.html