Ошибка HTTP 403 в методе POST с аутентификацией httpBasic с использованием Spring Security - PullRequest
0 голосов
/ 13 февраля 2019

Я сделал простой вызов API с базовым httpAuth:

 @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth)
            throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin").password(passwordEncoder().encode("admin")).roles("ADMIN")
                .and()
                .withUser("api").password(passwordEncoder().encode("api")).roles("API")
        ;
    }

    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/api/**").hasRole("API")
                .antMatchers("/admin/**").hasRole("ADMIN")
                .and().httpBasic()
        ;

    }

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

Кажется, это прекрасно работает со страницами администратора.Браузер запрашивает имя пользователя / пароль и предоставляет доступ.

Когда я пытаюсь использовать API, работает только метод GET.Это реализация:

 @RequestMapping(value = "/api/customerOrderConfirm", method = RequestMethod.POST)
    public ResponseEntity confirm(@RequestBody Activation activation) {
        try {
            ... do stuff
        } catch (Exception e) {
            logger.error("error executing command: " + e.toString(), e);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .contentType(MediaType.TEXT_PLAIN)
                    .body(e.toString());
        }
    }

    @RequestMapping(value = "/api/customerOrderConfirm", method = RequestMethod.GET)
    public ResponseEntity getConfirm() {
        return ResponseEntity.status(HttpStatus.OK)
                .body("OK");
    }

Это сообщения CURL. МЕТОД ПОЛУЧЕНИЯ:

$ curl -i --user api:api http://localhost:8012/api/customerOrderConfirm
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100     2  100     2    0     0      2      0  0:00:01 --:--:--  0:00:01    14
HTTP/1.1 200 OK
Date: Wed, 13 Feb 2019 18:07:37 GMT
Set-Cookie: JSESSIONID=node0oysb3zf7zfxr14nkdv8ezzhky6.node0;Path=/
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Content-Type: text/plain;charset=utf-8
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
X-Frame-Options: DENY
Content-Length: 2

OK

МЕТОД ПОЧТЫ:

$ curl -i --user api:api -d '{ }' -H 'Content-Type: application/json' http://localhost:8012/api/customerOrderConfirm
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   137    0   134  100     3    134      3  0:00:01 --:--:--  0:00:01  2914
HTTP/1.1 403 Forbidden
Date: Wed, 13 Feb 2019 18:07:25 GMT
Set-Cookie: JSESSIONID=node0169o0o7wk5u6v1ees33334z8uz5.node0;Path=/
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
X-Frame-Options: DENY
Content-Type: application/json;charset=utf-8
Transfer-Encoding: chunked

{"timestamp":"2019-02-13T18:07:25.830+0000","status":403,"error":"Forbidden","message":"Forbidden","path":"/api/customerOrderConfirm"}

1 Ответ

0 голосов
/ 13 февраля 2019

Я добавил в настройках безопасности:

.and().csrf().disable()

И теперь он работает

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...