Skip to content

INSRAM/Spring-Boot-Cors

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Spring Boot CORS Example

This project demonstrates how to configure CORS (Cross-Origin Resource Sharing) in a Spring Boot application using both annotations and Java configuration.


📌 Project Structure

src
 └── main
     └── java
         └── com.spring.services_cors
             ├── controller
             │    └── GreetingController.java
             ├── dto
             │    └── Greetings.java
             └── configuration
                  └── CorsConfiguration.java

🚀 Controller: GreetingController

@RestController
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    // CORS enabled with annotation
    @CrossOrigin(origins = "http://localhost:9000")
    @GetMapping("/greeting")
    public Greetings greetings(@RequestParam(defaultValue = "World") String name) {
        return new Greetings(counter.incrementAndGet(), String.format(template, name));
    }

    // CORS configured via JavaConfig
    @GetMapping("/greeting-javaconfig")
    public Greetings greetingsWithJavaConfig(@RequestParam(defaultValue = "World") String name) {
        return new Greetings(counter.incrementAndGet(), String.format(template, name));
    }
}

📦 DTO: Greetings

public class Greetings {

    private final long id;
    private final String content;

    public Greetings() {
        this.id = -1;
        this.content = "";
    }

    public Greetings(long id, String content) {
        this.id = id;
        this.content = content;
    }

    public long getId() {
        return id;
    }

    public String getContent() {
        return content;
    }
}

⚙️ Configuration: CorsConfiguration

@Configuration
public class CorsConfiguration {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                // Mapping for one endpoint
                registry.addMapping("/greeting-javaconfig")
                        .allowedOrigins("http://localhost:9000");

                // Mapping with specific methods
                registry.addMapping("/greeting-javaconfig")
                        .allowedOrigins("http://localhost:9000")
                        .allowedMethods("GET", "POST");

                // Mapping for users API
                registry.addMapping("/api/users/**")
                        .allowedOrigins("http://localhost:3000")
                        .allowedMethods("GET", "POST", "PUT", "DELETE");

                // Multiple origins
                registry.addMapping("/api/products/**")
                        .allowedOrigins("http://localhost:3000", "http://localhost:4200")
                        .allowedMethods("*");

                // Global CORS configuration (applies to all endpoints)
                registry.addMapping("/**")
                        .allowedOrigins("http://localhost:3000")
                        .allowedMethods("*"); // allow all HTTP methods
            }
        };
    }
}

🎯 Key Points About CORS

  • @CrossOrigin → Used directly on controller methods or classes for quick configuration.
  • WebMvcConfigurer → Centralized CORS configuration for multiple endpoints.
  • allowedOrigins("*") → Allows requests from any origin.
  • allowedMethods("*") → Allows all HTTP methods (GET, POST, PUT, DELETE, etc.).
  • Use global config when multiple endpoints require CORS.
  • Use annotation when only one or two APIs need CORS.

📝 Example Requests

  • With @CrossOrigin:

    GET http://localhost:8080/greeting?name=John
    Allowed Origin → http://localhost:9000
    
  • With Java Config:

    GET http://localhost:8080/greeting-javaconfig?name=John
    Allowed Origin → http://localhost:9000
    

🔑 Cheat Sheet (WebMvcConfigurer)

registry.addMapping("/api/**")
    .allowedOrigins("http://localhost:3000") // frontend origin
    .allowedMethods("GET", "POST", "PUT", "DELETE") // allowed HTTP methods
    .allowedHeaders("*") // allow all headers
    .exposedHeaders("Authorization") // expose specific headers
    .allowCredentials(true) // allow cookies/auth
    .maxAge(3600); // cache preflight response

✅ Run the Project

./mvnw spring-boot:run

Then access:


📚 References

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages