春季启动,Angular-无法处理POST请求

时间:2019-10-21 20:14:45

标签: angular spring-boot post spring-security

在我的应用程序中,我有一个POST请求,用户可以通过该请求保存其个人资料。 UI在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控制器中

@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();
    }

0 个答案:

没有答案