Why do you need @CrossOrigin Annotation in Spring boot ?

The @CrossOrigin annotation in Spring Boot is used to enable Cross-Origin Resource Sharing (CORS) for RESTful web services. CORS is a security mechanism that allows or restricts resources (like APIs) to be accessed from different domains.

By default, browsers block cross-origin requests for security reasons. To allow access, we need to configure CORS using @CrossOrigin or global configurations.

Basic Usage

1. Enable CORS on a Controller

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "http://example.com")  // Allows only example.com to access
public class MyController {

    @GetMapping("/data")
    public String getData() {
        return "CORS enabled response";
    }
}

Here, only http://example.com can access the API.

2. Enable CORS on Specific Method

@CrossOrigin(origins = "http://allowed-origin.com")
@GetMapping("/specific-data")
public String getSpecificData() {
    return "CORS enabled for specific origin";
}

This method only allows requests from http://allowed-origin.com.

3. Allow Multiple Origins

@CrossOrigin(origins = {"http://example.com", "http://another.com"})

This API allows requests from multiple domains.

4. Allow All Origins (*)

@CrossOrigin(origins = "*")

Not recommended for production, as it allows any website to access your API.

5. Set Allowed HTTP Methods

@CrossOrigin(origins = "http://example.com", methods = {RequestMethod.GET, RequestMethod.POST})

This API only allows GET and POST requests from http://example.com.

6. Global CORS Configuration (For All APIs)

Instead of adding @CrossOrigin on every controller, you can define global CORS settings.

Using WebMvcConfigurer

import org.springframework.context.annotation.Bean;
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 {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**")  // Applies to all endpoints under /api/
                        .allowedOrigins("http://example.com")  // Allow only this domain
                        .allowedMethods("GET", "POST", "PUT", "DELETE")  // Allowed HTTP methods
                        .allowedHeaders("*");  // Allow all headers
            }
        };
    }
}

This globally enables CORS for all "/api/**" endpoints.

Key Takeaways

  • @CrossOrigin allows controlling which domains can access the API.
  • Can be applied at the class level or method level.
  • Allows specific HTTP methods, headers, and origins.
  • Use Global CORS configuration for centralized control.

Real-World Example of @CrossOrigin in Spring Boot

You have a Spring Boot REST API running on http://localhost:8080, and a React/Angular frontend running on http://localhost:3000.
By default, browsers will block API requests due to CORS policy.
We will use @CrossOrigin to allow the frontend to access the backend.

Step 1: Create a REST Controller with @CrossOrigin

import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/products")
@CrossOrigin(origins = "http://localhost:3000")  // Allow frontend to access API
public class ProductController {

    @GetMapping
    public List getProducts() {
        return List.of("Laptop", "Phone", "Tablet");
    }
}

This allows only http://localhost:3000 to access GET /api/products.

Step 2: Calling API from Frontend (React)

fetch("http://localhost:8080/api/products")
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error("CORS Error:", error));

Without @CrossOrigin, the request fails with a CORS error in the browser.

Debugging CORS Issues

1. CORS Error in Browser Console

If you see an error like:

Access to fetch at 'http://localhost:8080/api/products' from origin 'http://localhost:3000' has been blocked by CORS policy.

Solution: Add @CrossOrigin to allow access.

2. Global CORS Configuration (Better Approach)

Instead of adding @CrossOrigin on every controller, use global configuration.

import org.springframework.context.annotation.Bean;
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 GlobalCorsConfig {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**")  // Apply to all endpoints under /api/
                        .allowedOrigins("http://localhost:3000")  // Allow frontend
                        .allowedMethods("GET", "POST", "PUT", "DELETE")  // Allowed HTTP methods
                        .allowedHeaders("*")  // Allow all headers
                        .allowCredentials(true);  // Allow cookies
            }
        };
    }
}

This centrally manages CORS for all /api/** endpoints.

Key Takeaways

  • Use @CrossOrigin for specific endpoints.
  • Use Global CORS Configuration for better maintainability.
  • Check browser console for CORS errors.
  • Enable allowCredentials(true) if using authentication.

Related Posts

Leave a Reply

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