Почему Spring Security Antmatcher всегда возвращается несанкционированным? - PullRequest
0 голосов
/ 03 апреля 2019

Я пытаюсь изучить Spring Security и создал простой контроллер. Я хочу включить POST для / всех конечных точек для неавторизованных пользователей и 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 Ответ

1 голос
/ 03 апреля 2019
  • Укажите способ аутентификации (пример: httpBasic())
  • Укажите PasswordEncoder (пример: 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();
   }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...