CORS不允许POST请求

时间:2020-07-03 11:28:05

标签: java angular rest jwt

我正在开发全栈应用程序,但遇到了问题。

我尝试从我的角度应用程序向Spring Boot后端应用程序执行POST请求,但是每次由于CORS而失败。实际上,如果我将POST更改为GET请求,它将始终成功。

这是我的前端代码:

    finalizeRegister(userAccount: UserAccount) {
    return this._httpClient.post(`${Constants.apiRoot}account/finalize`, userAccount);
    }

拦截器:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.url.startsWith(Constants.apiRoot)) {
  return from(this._authService.getAccessToken().then(token => {
    const headers = new HttpHeaders().set('Authorization', `Bearer ${token}`);
    const authReq = req.clone({ headers });
    return next.handle(authReq).pipe(tap(_ => { }, error => {
      var respError = error as HttpErrorResponse;
      if (respError && (respError.status === 401 || respError.status === 403)) {
        this._router.navigate(['/unauthorized']);
      }
    })).toPromise();
  }));
}
else {
  return next.handle(req);
}

}

Spring boot CORS配置:

 package pl.daniel.pawlowski.conquerorgame.security;

import com.auth0.spring.security.api.JwtWebSecurityConfigurer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.security.oauth2.jwt.*;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

/**
 * Configures our application with Spring Security to restrict access to our API endpoints.
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Value( "${auth0.audience}" )
    private String audience;

    @Value("${auth0.issuer}")
    private String issuer;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        JwtWebSecurityConfigurer
                .forRS256(audience, issuer)
                .configure(http)
                .authorizeRequests()
                .antMatchers(HttpMethod.POST, "/api/public").permitAll()
                .antMatchers(HttpMethod.GET, "/api/private").authenticated()
                .antMatchers(HttpMethod.GET, "/api/admin/**").hasAuthority("view:admin")
                .anyRequest()
                .authenticated()
                .and()
                .cors();
    }

    @Bean
    JwtDecoder jwtDecoder() {
        /*
        By default, Spring Security does not validate the "aud" claim of the token, to ensure that this token is
        indeed intended for our app. Adding our own validator is easy to do:
        */

        NimbusJwtDecoder jwtDecoder = (NimbusJwtDecoder)
                JwtDecoders.fromOidcIssuerLocation(issuer);

        OAuth2TokenValidator<Jwt> audienceValidator = new AudienceValidator(audience);
        OAuth2TokenValidator<Jwt> withIssuer = JwtValidators.createDefaultWithIssuer(issuer);
        OAuth2TokenValidator<Jwt> withAudience = new DelegatingOAuth2TokenValidator<>(withIssuer, audienceValidator);

        jwtDecoder.setJwtValidator(withAudience);

        return jwtDecoder;
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        configuration.setAllowedHeaders(Arrays.asList("Authorization"));
        return source;
    }


}

似乎我的配置有问题,因为当我尝试通过POST请求调用任何端点时,在我的浏览器控制台中我看到:

在以下位置访问XMLHttpRequest 原始来源的'http:// localhost:8081 / api / account / finalize' “ http:// localhost:4200”已被CORS政策阻止:请求 标头字段的内容类型不允许 飞行前响应中的Access-Control-Allow-Header。

2 个答案:

答案 0 :(得分:1)

您正在不同的端口上运行。 后端在http://localhost:4200上运行时,您的前端将从http://localhost:8081提供服务。

由于您在不同的端口上运行,因此请求被解释为来自不同的来源。它们在同一台机器/主机名上没关系,CORS会阻止它,因为这是它的指定方式。

要么禁用CORS,要么向您的HTTP响应添加Access-Control-Allow-Origin标头。

有关该主题的更多信息,请参见https://enable-cors.org/

答案 1 :(得分:0)

尝试允许禁用CROS,也可以根据您的实现来允许。参考:-https://howtodoinjava.com/spring5/webmvc/spring-mvc-cors-configuration/