What is the CORS ?
Lakmal Asela
Posted on September 16, 2024
CORS- Cross-Origin Resource Sharing-is a security feature used by web browsers. This feature stops a web page from requesting resources, or data, from a domain different from the one that served the web page. It is done to protect the users by disallowing malicious sites from sending unauthorized requests to servers or APIs at other domains.
How CORS Works
When a web page, in a certain origin, sends a request to a different origin, the browser first checks if the server allows this kind of cross-origin request. If it isn't so configured, the browser blocks the request. CORS defines a way in which a server can safely handle these cross-origin requests.
CORS relies on HTTP headers to let the server inform the browser whether or not the request is allowed. The key headers include:
Access-Control-Allow-Origin: Specifies which origin(s) are allowed to make requests (e.g., a specific domain or * for any domain).
Access-Control-Allow-Methods: Specifies which HTTP methods (e.g., GET, POST) are allowed.
Access-Control-Allow-Headers: Specifies which headers can be included in the request.
Access-Control-Allow-Credentials: Indicates whether credentials like cookies or authorization headers are allowed to be sent.
Why CORS is Used
Security: This is one of the most important features. It makes sure that there aren't any unauthorized requests allowed between different sites. A script originating from one domain is not allowed to access resources from another domain unless explicitly allowed.
Controlled Sharing: This is a controlled exposure to resources from other origins, notably in cases when APIs or services are consumed by applications hosted over different domains.
CORS Implementation in Spring Boot
Global Configuration
package com.logmaven.exmaven.configuration;
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 WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
// Allowing CORS requests from http://localhost:3000
registry.addMapping("/**") // Apply to all endpoints
.allowedOrigins("http://localhost:3000") // Allow requests from this origin
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // Allow these HTTP methods
.allowedHeaders("*") // Allow all headers
.allowCredentials(true); // Allow credentials like cookies
}
}
CORS Configuration Using Spring Security
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
@EnableWebSecurity
public class WebSecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable() // Enable CORS and disable CSRF for simplicity
.authorizeRequests()
.anyRequest().authenticated(); // Allow only authenticated requests
return http.build();
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("http://localhost:3000");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
This configuration enables CORS for all endpoints, allowing requests from http://localhost:3000. You can adjust it to your specific requirements, including credentials, headers, and allowed HTTP methods.
Advantages of CORS
Security Control: Prevents unauthorized cross-origin requests.
Granular Access: Allows fine-grained access to resources based on origin, methods, and headers.
Interoperability: This allows modern web applications to securely consume APIs and services from different origins.
Posted on September 16, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.