为什么Spring Security antmatcher总是未经授权返回?

时间:2019-04-03 13:24:03

标签: spring spring-boot spring-security

我正在尝试学习Spring Security并创建了一个简单的控制器。我想为未经授权的用户启用POST到/ all端点,并为具有USER角色的用户启用POST到/ user。由于某种原因,我的代码总是返回未经授权的403。

控制器

public class Controller {

    @PostMapping("/all")
    public ResponseEntity<Object> all() {
        return new ResponseEntity<>("all", HttpStatus.OK);
    }

    @PostMapping("/user")
    public ResponseEntity<Object> user() {
        return new ResponseEntity<>("user", HttpStatus.OK);
    }
}

安全配置

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                    .antMatchers(HttpMethod.POST, "/all").permitAll()
                    .antMatchers(HttpMethod.POST, "/user").hasRole("USER");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("user").password("user").roles("USER");
    }

}

1 个答案:

答案 0 :(得分:1)

  • 提供一种验证方式(例如:httpBasic()
  • 提供密码编码器(例如:BCryptPasswordEncoder

将它们放在一起,您的配置应如下所示:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

   @Override
   protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeRequests()
            .antMatchers(HttpMethod.POST, "/all").permitAll()
            .antMatchers(HttpMethod.POST, "/user").hasRole("USER")
            .and().httpBasic();
   }

   @Override
   protected void configure(AuthenticationManagerBuilder auth) throws Exception {
       auth.inMemoryAuthentication()
           .withUser("user")
           .password(encoder().encode("user"))
           .roles("USER");
   }

   @Bean
   public PasswordEncoder encoder() {
       return new BCryptPasswordEncoder();
   }
}