CORS Origin Spring Boot Jhipster - pre-flight fails

只愿长相守 提交于 2019-12-06 05:28:36

问题


I am using jhipster v2.27.2 I have enabled cors by uncommenting the lines in the application.yml

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

In the "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);
    }

But still when I request for the access token, I see this error

http://localhost:8080/oauth/token?username=admin&password=admin&grant_type=password&scope=read. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9090' is therefore not allowed access. The response had HTTP status code 401.


回答1:


Looks like in the default SecurityConfiguration, its not skipping security check for OPTIONS.

Try adding the following antMatcher to the protected void configure(HttpSecurity http) method in SecurityConfiguration.java

.antMatchers(org.springframework.http.HttpMethod.OPTIONS, "/api/**").permitAll()



回答2:


sometimes this issue will come if you forget to register cors on specified URLs.In WebConfigurer look for corsFilter and and add these line

 log.debug("Registering CORS filter");
        source.registerCorsConfiguration("/api/**", config);



回答3:


Another option in the SecurityConfiguration.java. Instead of using antMatcher within the configure(HttpSecurity) override, is to add it within the configure(WebSecurity) override...

public void configure(WebSecurity web) throws Exception {
    web.ignoring()
        .antMatchers(HttpMethod.OPTIONS, "/**")


来源:https://stackoverflow.com/questions/36142155/cors-origin-spring-boot-jhipster-pre-flight-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!