Skip to main content

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

Popular posts from this blog

a simple example for jdbc PreparedStatement

a simple example for PreparedStatement package basics.in.java.blogspot.in; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class Main { private static final String USERNAME="root"; private static final String PASSWORD=""; private static final String CONN_STRING="jdbc:mysql://localhost/basicsinjavablogspot"; public static void main(String[] args) throws ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver"); Connection conn=null; Statement stmt=null; ResultSet rs=null; try { conn= DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD); System.out.println("database connection successful"); //stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); String sql="select * fr...

Server-Side Pagination with React-Table and Spring Boot JPA with H2 Database

Pagination is a common technique used to split large amounts of data into smaller, more manageable chunks. With server-side pagination, data is retrieved from the server in smaller batches, reducing the amount of data transferred over the network and improving application performance. React-Table provides a wide range of built-in features such as sorting, filtering, pagination, row selection, and column resizing. These features can be easily configured and customized to fit specific requirements. For example, you can customize the sorting behavior to handle multiple sorting criteria, or you can add custom filters to the table to handle complex data filtering scenarios. Additionally, React-Table provides a flexible API that allows developers to extend its functionality with custom hooks, plugins, and components. This means that you can easily add custom functionality to the table, such as exporting data to CSV or integrating with external data sources. In terms of styl...