Enabling CORS in a Spring Boot Application(access to xmlhttprequest at blocked by cors policy fix): A Complete Guide with Code Examples
Enabling CORS in a Spring Boot Application
Cross-Origin Resource Sharing (CORS) is a security feature implemented by web browsers that restricts web pages from making requests to a different domain than the one that served the web page. This is a common issue when building Single Page Applications (SPAs) or consuming RESTful APIs from different domains. In this blog post, we'll look at how to enable CORS in a Spring Boot application.
Step 1: Add CorsFilter Bean
The first step to enabling CORS in a Spring Boot application is to create a CorsFilter
bean. Here's how:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import java.util.Arrays;
@Configuration
public class CorsConfig {
@Value("${cors.allowed.origins}")
private String[] allowedOrigins;
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(Arrays.asList(allowedOrigins));
config.setAllowedMethods(Arrays.asList("*"));
config.setAllowedHeaders(Arrays.asList("*"));
config.setAllowCredentials(true);
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
In the above code, we create a CorsFilter
bean and set its configuration to allow all origins, methods, and headers. We also enable credentials, which means that cookies and other sensitive information can be sent with the request.
Note that we are using a @Value
annotation to inject the allowed origins from the application properties file. This allows us to configure the allowed origins dynamically without changing the code.
Step 2: Configure Allowed Origins
The next step is to configure the allowed origins for your API. This can be done in the application properties file:
cors.allowed.origins=http://localhost:4200
The above code allows requests from http://localhost:4200
. You can replace this with any domain or a list of domains that are allowed to access your API. You can also set the value to *
to allow all domains, but this is generally not recommended for security reasons.
Step 3: Test the CORS Configuration
Now that we have enabled CORS in our Spring Boot application, let's test it by making a request from a different domain. For this example, let's assume that we have an Angular application running on http://localhost:4200
and we want to make a request to our Spring Boot API running on http://localhost:8080
.
Here's an example Angular service that makes a GET request to the API:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ApiService {
private API_URL = 'http://localhost:8080/api';
constructor(private http: HttpClient) { }
getSomeData(): Observable {
return this.http.get(${this.API_URL}/data);
}
}
If we try to make a request to the API from our Angular application, we'll see an error in the browser console:
Access to XMLHttpRequest at 'http://localhost:8080/api/data' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
This error occurs because our Angular application is running on a different domain than our Spring Boot API, and the browser has blocked the request due to the CORS policy.
To fix this error, we need to enable CORS in our Spring Boot API. Now that we have followed the above steps, we can try making the same request again. This time, we should see the response from our API without any CORS errors.
Conclusion
In this blog post, we looked at how to enable CORS in a Spring Boot application. By adding a CorsFilter
bean and configuring the allowed origins in the application properties file, we can easily allow requests from different domains to our API.
Comments
Post a Comment