Spring Boot, Angular - не обрабатывает запрос POST - PullRequest
0 голосов
/ 21 октября 2019

В моем приложении у меня есть POST-запрос, с помощью которого пользователь может сохранить свой профиль. Пользовательский интерфейс находится на Angular 6. Серверная часть находится в Spring Boot. Использование JWT для аутентификации каждого запроса после входа в систему.

Когда я отправляю запрос POST, это то, что я вижу в браузере. Второй запрос, который является профилем, должен быть POST, но я не знаю, почему он отображается как запрос GET, а код состояния - 302

enter image description here

Ниже приведен код в Angular для отправки пост-запроса

saveProfile(updatedCountries: string[]) {
    return this.http
      .post(`${environment.apiUrl}/user/profile`, updatedCountries)
      .pipe(first())
      .subscribe(data => {
        data['error'] !== ''
          ? this.alertService.error(data['error'], true)
          : this.alertService.success(data['message'], true);
      });
  }

Следующий код находится в Spring Boot controller

@RequestMapping(value = "/profile", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    public GenericResponse saveProfile(@RequestBody List<String> updatedCountries, JwtRequest jwtRequest) {
        userService.saveUserProfile(jwtRequest.getEmail(), updatedCountries);

        return new GenericResponse("User profile successfully save");
    }

Ниже приведен WebSecurityConfig

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

protected void configure(HttpSecurity http) throws Exception {
        http.addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class)
                .addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class)
                .csrf()
                .csrfTokenRepository(csrfTokenRepository())
                .ignoringAntMatchers(CSRF_IGNORE)
                .and()
                .addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class)
                .cors()
                .and()
                .authorizeRequests()
                .antMatchers("/resources/**", "/user/register", "/user/registrationConfirm*", "/user/authenticate")
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .logout()
                .permitAll()
                .and()
                .sessionManagement()
                .invalidSessionUrl("/invalidSession")
                .maximumSessions(1)
                .sessionRegistry(sessionRegistry())
                .and()
                .sessionFixation()
                .none();

        http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
    }


@Bean
    public CorsConfigurationSource corsConfigurationSource() {
        final CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
        configuration.setAllowedMethods(Arrays.asList("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"));

        // setAllowCredentials(true) is important, otherwise:
        // The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*'
        // when the request's credentials mode is 'include'.
        configuration.setAllowCredentials(true);

        // setAllowedHeaders is important! Without it, OPTIONS preflight request
        // will fail with 403 Invalid CORS request
        configuration.setAllowedHeaders(Arrays.asList("Authorization", "Cache-Control", "Content-Type", "x-xsrf-token"));
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    private CsrfTokenRepository csrfTokenRepository() {
        HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
        repository.setHeaderName("X-XSRF-TOKEN");
        return repository;
    }


    /**
     * Configure AuthenticationManager so that it knows from where to load
     * user form matching credentials
     *
     * @param auth
     * @throws Exception
     */
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    public SessionRegistry sessionRegistry() {
        return new SessionRegistryImpl();
    }
...