How to enable CORS (Cross Origin Resource Sharing) for specific domains in Spring Boot?

For security reasons, browsers don’t allow javascript code to call APIs deployed in domains other than the current domain in which the javascript code is deployed.

So if your javascript code is in a.com you cannot call an API deployed in b.com.

So if you have deployed an API developed in Spring Boot in b.com , you cannot call it through javascript from your browser.

How can you overcome this?

This can be overcome by adding appropriate HTTP headers in your API response from b.com.

How to do this in Spring Boot?

Just add @CrossOrigin annotation on all the rest controller methods you want to be accessed outside of its domain.

Like this:

package com.example.demo;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

	
	@CrossOrigin
	@GetMapping("/greet")
	public String sayHello() {
		
		return "Hello";
	}
}

In the above method , the annotation @CrossOrigin makes the API sayHello() accessible outside the domain where the above code is deployed. Spring Boot will add necessary headers. But it makes it accessible to any domain outside of the current domain.

How to allow cross origin requests for only specific domains?

Let’s say you want to allow only the domain where your UI code(javascript) is deployed to access your REST API.

This can be done by creating a configuration class and configuring your domains there:

package com.example.demo;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration

public class CorsConfig implements WebMvcConfigurer {

	@Override
	public void addCorsMappings(CorsRegistry registry) {

		registry.addMapping("/greet").allowedOrigins("http://localhost").allowedMethods("GET");
	}
}

You need to implement WebMvcConfigurer interface and override the method addCorsMappings().

Inside that method add the URLs you want to allow using addMapping() method , the domains you want to allow using allowedOrigins() method and the type of REST methods you want to allow using allowedMethods() method. Both allowedOrigins() and allowedMethods() accept an array of strings , so you can pass multiple parameters.

In the above case I have configured localhost domain as that is where I deployed my UI code (on Apache Http server , default port 80)

That’s it!

Here is a demo with and without the above config.

Without the config , I tried to call the above API deployed at localhost:8080 from Apache Server localhost:80 (notice even if port names are different they are considered as different origins) using the below javascript code:

<html>

<script>

async function test(){

 let response = await fetch('http://localhost:8080/greet');
  
  let data = await response.text();

  console.log(data);
  
}

test();


</script>
    
</html>

And I got the below error in browser console:

I added the above Configuration file and then tried to call it from the javascript code:

I got the output “Hello”.(ignore the warnings starting with DevTools)

That’s it!


Posted

in

,

by

Comments

Leave a Reply

Discover more from The Full Stack Developer

Subscribe now to keep reading and get access to the full archive.

Continue reading