HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Spring 5 / Spring WebMVC / CORS with Spring

CORS with Spring

CORS (Cross-origin resource sharing) allows a webpage to request additional resources into browser from other domains e.g. fonts, CSS or static images from CDN. CORS helps in serving web content from multiple domains into browsers who usually have the same-origin security policy.

In this example, we will learn to enable Spring CORS support in Spring MVC application at method level and global level.

Read More: Java CORS Filter Example

Table of Contents

1. Spring CORS - Method level with @CrossOrigin
2. Spring CORS - Global CORS configuration

1. Spring CORS – Method level with @CrossOrigin

Spring MVC provides @CrossOrigin annotation. This annotation marks the annotated method or type as permitting cross origin requests.

1.1. Spring CORS allow all

By default, @CrossOrigin allows all origins, all headers, the HTTP methods specified in the @RequestMapping annotation and a maxAge of 30 minutes.

You can override default CORS settings by giving value to annotation attributes :

AttributeDescription
originsList of allowed origins. It’s value is placed in the Access-Control-Allow-Origin header of both the pre-flight response and the actual response.

  • "*" – means that all origins are allowed.
  • If undefined, all origins are allowed.
allowedHeadersList of request headers that can be used during the actual request. Value is used in preflight’s response header Access-Control-Allow-Headers.

  • "*" – means that all headers requested by the client are allowed.
  • If undefined, all requested headers are allowed.
methodsList of supported HTTP request methods. If undefined, methods defined by RequestMapping annotation are used.
exposedHeadersList of response headers that the browser will allow the client to access. Value is set in actual response header Access-Control-Expose-Headers.

  • If undefined, an empty exposed header list is used.
allowCredentialsIt determine whether browser should include any cookies associated with the request.

  • false – cookies should not included.
  • " " (empty string) – means undefined.
  • true – pre-flight response will include the header Access-Control-Allow-Credentials with value set to true.
  • If undefined, credentials are allowed.
maxAgeMaximum age (in seconds) of the cache duration for pre-flight responses. Value is set in header Access-Control-Max-Age.

  • If undefined, max age is set to 1800 seconds (30 minutes).

1.2. @CrossOrigin at Class/Controller Level

@CrossOrigin(origins = "*", allowedHeaders = "*")
@Controller
public class HomeController 
{
	@GetMapping(path="/")
	public String homeInit(Model model) {
		return "home";
	}
}

Read More – Spring 5 MVC Example

1.3. @CrossOrigin at Method Level

@Controller
public class HomeController 
{
	@CrossOrigin(origins = "*", allowedHeaders = "*")
	@GetMapping(path="/")
	public String homeInit(Model model) {
		return "home";
	}
}

1.4. @CrossOrigin Overridden at Method Level

homeInit() method will be accessible only from domain http://example.com. Rest other methods in HomeController will be accessible from all domains.

@Controller
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class HomeController 
{
	@CrossOrigin(origins = "http://example.com")
	@GetMapping(path="/")
	public String homeInit(Model model) {
		return "home";
	}
}

2. Spring CORS – Global CORS configuration

2.1. Implement WebMvcConfigurer

To enable CORS for the whole application, use WebMvcConfigurer to add CorsRegistry.

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
public class CorsConfiguration implements WebMvcConfigurer
{
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("GET", "POST");
    }
}

2.2. WebMvcConfigurer Bean

In spring boot application, it is recommended to just declare a WebMvcConfigurer bean.

@Configuration
public class CorsConfiguration 
{
    @Bean
    public WebMvcConfigurer corsConfigurer() 
    {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("http://localhost:8080");
            }
        };
    }
}

2.3. CORS with Spring Security

To enable CORS support through Spring security, configure CorsConfigurationSource bean and use HttpSecurity.cors() configuration.

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.cors().and()
			//other config
	}

	@Bean
	CorsConfigurationSource corsConfigurationSource() 
	{
		CorsConfiguration configuration = new CorsConfiguration();
		configuration.setAllowedOrigins(Arrays.asList("https://example.com"));
		configuration.setAllowedMethods(Arrays.asList("GET","POST"));
		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		source.registerCorsConfiguration("/**", configuration);
		return source;
	}
}

Drop me your questions in comments section.

Happy Learning !!

Sourcecode Download

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Rioh Rowe

    April 24, 2020

    This is really great. Exactly what I was looking for. Unfortunately, It did not work for what I am working on. I am attempting to implement SOAP using Spring Boot, and when I try and grab the WSDL from my angular project, I get A CORS Policy violation. The WSDL is generated automatically by Spring Boot and made available as an endpoint by a MessageDispatcherServlet:

    package com.rioh.endpoints.configuration;
    
    import org.springframework.boot.web.servlet.ServletRegistrationBean;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.core.io.ClassPathResource;
    import org.springframework.web.bind.annotation.CrossOrigin;
    import org.springframework.web.servlet.config.annotation.CorsRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    import org.springframework.ws.config.annotation.EnableWs;
    import org.springframework.ws.transport.http.MessageDispatcherServlet;
    import org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition;
    import org.springframework.xml.xsd.SimpleXsdSchema;
    import org.springframework.xml.xsd.XsdSchema;
    
    @Configuration
    @EnableWs
    public class RoutesEndpointConfig
    {
    
    	@Bean
    	public ServletRegistrationBean messageDispatcherServlet(ApplicationContext context)
    	{
    		MessageDispatcherServlet servlet = new MessageDispatcherServlet();
    		servlet.setApplicationContext(context);
    		servlet.setTransformWsdlLocations(true); 
    		return new ServletRegistrationBean(servlet, "/ws/*");
    	}
    	@Bean(name = "Routes")
    	public DefaultWsdl11Definition defaultWsdl11DefinitionAddRoute(XsdSchema schema)
    	{
    		DefaultWsdl11Definition defaultWsdl11Definition = new DefaultWsdl11Definition();
    		defaultWsdl11Definition.setPortTypeName("Routes");
    		defaultWsdl11Definition.setLocationUri("/ws");
    		defaultWsdl11Definition.setTargetNamespace("http://www.rioh.Route.webservice");
    		defaultWsdl11Definition.setSchema(schema);
    		return defaultWsdl11Definition;
    	}
    	
    	@Bean
    	public XsdSchema schema()
    	{
    		return new SimpleXsdSchema(new ClassPathResource("RouteSoapMeta.xsd"));
    	}
    	
    }
    

    Even when using the global CORS configuration, I still get the “Blocked by cors policy” error in my browser when I try and access it from my angular project.

  2. abhijit

    March 26, 2020

    cors is not working for POST method. almost tried all the methods

  3. Rao

    February 22, 2020

    “WebSecurityConfigurerAdapter”

    Have you tested this code.

    WebSecurityConfigurerAdapter is deprecated with Spring 5 and Spring Boot 2.0.

    Adifferent appraoch has to be used.

    • Mach

      April 9, 2020

      which one ? , please explain if you know working solution.

  4. surya

    October 31, 2019

    Somehow every code base on Spring Boot 2 Security including the examples on “Spring.io” work only on localhost.

    Looks like there is some undocumented code base related to CORS. Because the document approach fails in staging hence cannot be enhanced and promoted to production.

    None work in Production or staging environment.

    I have tested this code base and various others on code bases on AWS, Azure, Google and other cloud vendors.

    Somehow all sample code-bases work excellently on local host.

    On staging it is failure.

    I have tried two scenarios the application front-end on a different physical instance on Apache httpd and java Rest Services on a different physical instance with Tomcat.

  5. Vikram

    September 23, 2019

    Sorry for asking such a basic question, but to what does “/**” refer in addMapping()? Allowed origins? Allowed headers?

    • Lokesh Gupta

      September 24, 2019

      This is a path pattern that used in Apache ant which spring team uses in whole framework.

      • ? matches one character
      • * matches zero or more characters
      • ** matches zero or more ‘directories’ in a path

      Ref : SO Thread

  6. Jayapriya

    May 10, 2019

    Hi,

    I’m trying you integrate angular js with spring boot. I’m getting cross origin error at angular js side after the call returns from rest service. Will this snippet add header to the response? It seems it’s not working in my code.

    thanks,
    jayapriya

    • Hamid

      April 16, 2020

      I have this problem too. I have no idead how to fix it

  7. Satish

    April 3, 2019

    In HttpSecurity cors() method does not present To enable CORS support through Spring security?

  8. Lucifer

    March 27, 2019

    I got error at http.cors() cors() not defined. Please help.

  9. Gustavo S

    April 19, 2018

    Hi, greate example and it works perfect, but I have updated my code base to spring 5 and spring boot 2 and that code is shown as deprecated. I have modified the implementation and all works fine but i have a problem when a the originating request is coming from a domain bound to a port like localhost:3001 (example

  10. Balaji

    January 9, 2018

    Hi thanks for your valuable example, i have enables cors for spring security in XML, but i am getting 401 unauthorised problem of preflight request with OPTIONS method. I am using spring security and wildfly server.

Comments are closed on this article!

Search Tutorials

Spring 5 Tutorial

  • Spring 5 – Introduction
  • Spring 5 – New Features
  • Spring 5 – Bean Java Config
  • Spring 5 – Bean XML Config
  • Spring 5 – Eager vs Lazy Init
  • Spring 5 – DispatcherServlet
  • Spring 5 – MVC Annotations
  • Spring 5 – MVC + Hibernate
  • Spring 5 – CORS
  • Spring 5 – Security Java Config
  • Spring 5 – Custom Login Form

Spring Tutorial

  • Spring – Introduction
  • Spring – IoC Containers
  • Spring – IoC vs. DI
  • Spring – Bean Scopes
  • Spring – Bean Life Cycle
  • Spring – Bean Postprocessors
  • Spring – Autowiring
  • Spring – Annotations
  • Spring – Stereotype Annotations
  • Spring – Task Scheduling
  • Spring – Timer Task
  • Spring – Events
  • Spring – Message Source
  • Spring – ResourceLoader
  • Spring – Property Editor
  • Spring – Send Email
  • Spring – Version-less Schema
  • Spring – Interview Questions
  • Spring – Best Practices

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces