×
☰ See All Chapters

Configuring Cross-Origin Requests in Spring Security for Inter-Domain Communication

In certain situations, despite the ease of using the @CrossOrigin annotation, managing CORS (Cross-Origin Resource Sharing) configuration in a centralized manner might be more desirable. This centralization facilitates easier maintenance and enhances clarity of the CORS settings across the application.

To achieve this, one can modify the configuration class to apply CORS configuration using a Customizer. This alternative approach allows for defining CORS configurations in one place, streamlining the management process.

In the upcoming example, modifications will be made to the configuration class to specify the allowed origins. This change will enable a more consolidated and systematic management of CORS configuration within the application.

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {

   
@GetMapping(value = "/hello")
   
public String sayHello() {
       
return "Hello!";
   }

   
@PostMapping(value = "/hello")
   
public String sayHelloPost() {
       
return "Hello!";
   }

}

 

package com.java4coding;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class ApplicationWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

   
@Override
   
protected void configure(HttpSecurity http) throws Exception {
       http.httpBasic();
       http.authorizeRequests()
               .anyRequest().permitAll();
       http.csrf().disable();
   }

}

 

When configuring CORS (Cross-Origin Resource Sharing) in Spring Security, the cors() method invoked from the HttpSecurity object requires a Customizer<CorsConfigurer> object as a parameter. This Customizer object is used to set up a CorsConfigurationSource, which provides a CorsConfiguration for each HTTP request.

The CorsConfiguration object specifies the allowed origins, methods, and headers for CORS requests. It's crucial to specify at least the allowed origins and methods when using this approach. If only the origins are specified without any methods, the application will not allow requests. This is because, by default, a CorsConfiguration object does not define any methods. Therefore, it's necessary to explicitly configure the allowed methods alongside the origins to enable CORS functionality effectively.

 


All Chapters
Author