0

I've got an api configured with Spring Boot on my localhost. My Spring Boot controller should allow CORS requests, as I'm working with @CrossOrigin:

@RestController
@CrossOrigin
@RequestMapping("/api")
public class imageController {
    @GetMapping("/images")
    public List<Image> findAll(){
        return imageService.findAll();
    }
}

When testing with Postman / cURL everything is working fine (but cURL doesn't care about CORS policies...). Now I'm trying to access the ressource 'http://localhost:8081/api/images' from my React application with axios. I get following response-header, which determines that the request was blocked because of CORS (see 'X-XSS-Protection').

Cache-Control
    no-cache, no-store, max-age=0, must-revalidate
Connection
    keep-alive
Date
    Tue, 23 Mar 2021 11:10:54 GMT
Expires
    0
Keep-Alive
    timeout=60
Pragma
    no-cache
Set-Cookie
    JSESSIONID=0683F0AD7647F9F148C9C2D4CED8AFE6; Path=/; HttpOnly
Transfer-Encoding
    chunked
Vary
    Origin
Vary
    Access-Control-Request-Method
Vary
    Access-Control-Request-Headers
WWW-Authenticate
    Bearer realm="Unknown"
X-Content-Type-Options
    nosniff
X-Frame-Options
    DENY
X-XSS-Protection
    1; mode=block

My axios request looks like this:

function findAll() {
    return instance.get('/api/images')
}

const instance = axios.create({
    baseURL: `${config.API_BASE_URL}`,
    headers: {
        'Content-Type': 'application/json'
    }
})

instance.interceptors.request.use(request => {
    console.log('Starting Request', JSON.stringify(request, null, 2))
    return request
})

instance.interceptors.response.use(response => {
    console.log('Response:', JSON.stringify(response, null, 2))
    return response
})

...and it's called by following code:

    componentDidMount() {
        this.setState({ isLoading: true })
        ImageService.authToken(keycloak.token)
        ImageService.findAll().then((res) => {
            this.setState({ images: res.data, isLoading: false });
        });
    }

How do I configure Spring Boot to allow such requests and not blocking my request by CORS policies?

Note, that my application is secured by keycloak. But I dont think the configuration of keycloak is relevant for this case. Please let me know if you need the Spring Boot configuration of keycloak.

2 Answers 2

1

Hi you need to create a global cors configuration in your spring boot project.Create a class and annotate it with @Configuration. You can follow this example below.

@Configuration
public class MyConfiguration {

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
           registry.addMapping("/api/**")
              .allowedOrigins("http://domain2.com")
              .allowedMethods("PUT", "DELETE")
              .allowedHeaders("header1", "header2", "header3")
              .exposedHeaders("header1", "header2")
              .allowCredentials(false).maxAge(3600);
        }
    };
  }
}

Here is the full guide that spring framework provides https://spring.io/blog/2015/06/08/cors-support-in-spring-framework

Sign up to request clarification or add additional context in comments.

Comments

1

Do you maybe have a Spring security configuration (@EnableWebSecurity / @EnableSpringSecurity) in place that may be interfering ? If so, you could configure cors() there as well.

@Configuration
@EnableWebSecurity
@EnableSpringSecurity
class WebSecurityConfiguration(...)


  override fun configure(http: HttpSecurity) {
        http.cors().configurationSource {
                CorsConfiguration().apply {
                    allowedOrigins = listOf("*")
                    allowedMethods = listOf("GET", "OPTIONS")
                    allowedHeaders = listOf("*")
                }
            }

Also see https://docs.spring.io/spring-security/site/docs/4.2.19.BUILD-SNAPSHOT/reference/html/cors.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.