1. Overview

In this article, We will learn Spring Rest service allow Cross Origin or @CrossOrigin Example with spring rest service. Let me explain what is Cross-Origin, Cross-Origin indicate allowed to access the resource from another domain.

CORS means  Cross-Origin Resource Sharing (CORS), we have explained multiple ways with an example o allowed CORS in spring Rest API or Spring boot Rest API.

Why should we allow CROS?

For example, Our backend application is running in http://localhost:8080 and our UI application is running on http://localhost:4200.  So when UI try to access any web service then spring rest API does not allow to access from another host or domain. If your UI in angular then it will throw an exception like:

“No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:4200’ is therefore not allowed access.”

To avoid the above problem we should register CROS domains to spring application so it will be allowed other domain request also.

@CrossOrigin is annotation using that we can be allowed cross-origin and we also allow cross-origin for all rest API.

2. Example

In this examples, we have explained @CrossOrigin annotation at Controller Method level, @CrossOrigin annotation at the Controller level, Cross Origin at global or for all rest API,  Cross Origin with spring security.

1. @CrossOrigin Annotation

To allowed Cross-Origin for individual service then we can use @CrossOrigin annotation at Controller Level.

  • @CrossOrigin(origins = "*") allowed all domain
  • @CrossOrigin(origins = {"http://www.example1.com","http://www.example2.com"}) allowed for multiple domains
@RestController
public class EmployeeController {
    @CrossOrigin(origins = "http://localhost:4200")         // for individual controller, allowed all request from localhost:4200
    @RequestMapping("/getEmployees")
    public List<Employee> getEmployees() {
        return Employee.getEmployee();
    }
}

2. @CrossOrigin on Controller

We can use @CrossOrigin at the controller level which will be applied to all the Controller method insider it so no need to write @CrossOrigin at each and every method.

NOTE: Use * for all domains. 

  • @CrossOrigin(origins = "*") allowed all domain
  • @CrossOrigin(origins = {"http://www.example1.com","http://www.example2.com"}) allowed for multiple domains
package com.javadeveloperzone.controller;
import com.javadeveloperzone.model.Employee;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
 * Created by JavaDeveloperZone on 19-07-2017.
 */
@RestController
@CrossOrigin(origins = "http://localhost:4200")         // for all controller inside this class, allowed all request from localhost:4200
public class EmployeeController {
    @RequestMapping("/getEmployees")
    public List<Employee> getEmployees() {
        return Employee.getEmployee();
    }
    @DeleteMapping("/delete/{id}")
    public List<Employee> getEmployees(@PathVariable("id")long id) {
        return Employee.getEmployee();
    }
}

3. Allowed CORS for all rest API

Here we have configured bean for WebMvcConfigurerAdapter and add addMapping and allowedOrigins which indicates those URL can be accessible from those origins.

  • registry.addMapping("/api/**").allowedOrigins("*");  for /api/** means all URL start with /api/*, and * for all domain
  • registry.addMapping("/api/**").allowedOrigins("http://www.example.com");  for /api/** means all URL start with /api/*, and allowed for http://www.example.com
  • registry.addMapping("/api/**").allowedOrigins("http://www.example.com").allowedMethods("PUT", "DELETE")
    for specific method type

package com.javadeveloperzone;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
 * Created by JavaDeveloperZone on 28-07-2018.
 */
@SpringBootApplication
@ComponentScan // Using a root package also allows the @ComponentScan annotation to be used without needing to specify a basePackage attribute
public class SpringBootConfig {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(SpringBootConfig.class, args);            // it wil start application
    }
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("*"); // for /** means all mapping URL, and * for all domain
            }
        };
    }
}

4. CORS with Spring Security

While working with spring security then we can configure cross-origin as follow, For more details spring security cross document

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      // by default uses a Bean by the name of corsConfigurationSource
      .cors().and()
      ...
  }
  @Bean
  CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("http://example.com"));
    configuration.setAllowedMethods(Arrays.asList("GET","POST"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
  }
}

4. Concussion

In this article, We learned that how we can allowed request from another domain in spring rest API. It is the concept of spring web so using the same configuration we can implement in spring boot rest API or any other spring web API.

5. References

6. Source Code

spring-boot-cross-origin-example (70 KB)

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *