CORS Origin Spring Boot Jhipster - 飞行前失败

i_r*_*aqz 4 yaml cors spring-boot jhipster

我正在使用jhipster v2.27.2我通过取消注释application.yml中的行来启用cors

jhipster:
async:
    corePoolSize: 2
    maxPoolSize: 50
    queueCapacity: 10000

cors: #By default CORS are not enabled. Uncomment to enable.
    allowed-origins: "*"
    allowed-methods: GET, PUT, POST, DELETE, OPTIONS
    allowed-headers: "*"
    exposed-headers:
    allow-credentials: true
    max-age: 1800
Run Code Online (Sandbox Code Playgroud)

在"WebConfigurer"中

@Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = props.getCors();
        if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) {
            source.registerCorsConfiguration("/api/**", config);
            source.registerCorsConfiguration("/v2/api-docs", config);
            source.registerCorsConfiguration("/oauth/**", config);
        }
        return new CorsFilter(source);
    }
Run Code Online (Sandbox Code Playgroud)

但是当我请求访问令牌时,我看到了这个错误

http:// localhost:8080/oauth/token?username = admin&password = admin&grant_type = password&scope = read.对预检请求的响应未通过访问控制检查:请求的资源上不存在"Access-Control-Allow-Origin"标头.因此不允许来源' http:// localhost:9090 '访问.响应具有HTTP状态代码401.

小智 7

看起来在默认情况下SecurityConfiguration,它不会跳过OPTIONS的安全检查.

尝试将以下内容添加antMatcher到protected void configure(HttpSecurity http)方法中protected void configure(HttpSecurity http)

.antMatchers(org.springframework.http.HttpMethod.OPTIONS, "/api/**").permitAll()
Run Code Online (Sandbox Code Playgroud)