DEV Community

loizenai
loizenai

Posted on

Spring Boot – CORS Support using XML Config

https://grokonez.com/spring-framework/spring-boot/spring-boot-cors-support-using-xml-config

Spring Boot – CORS Support using XML Config

In previous post, we have created a REST Service with Global CORS Configuration using Java Config. This tutorial will introduce way to define global CORS configuration out of our Controller with XML Config in Spring Boot example.

Related Articles:

I. Global CORS Configuration using XML Config

Spring provides a way that uses XML Config applying for all REST Service Controllers in our project:

<mvc:cors>
    <mvc:mapping path="/customers"
        allowed-origins="http://localhost:8484, http://localhost:9000"
        allowed-methods="POST, GET, PUT, DELETE"
        allowed-headers="Content-Type"
        exposed-headers="header-1, header-2"
        allow-credentials="false"
        max-age="6000" />
</mvc:cors>
  • allowedOrigins: specifies the URI that can be accessed by resource. "*" means that all origins are allowed. If undefined, all origins are allowed.

  • allowCredentials: defines the value for Access-Control-Allow-Credentials response header. If value is true, response to the request can be exposed to the page. The credentials are cookies, authorization headers or TLS client certificates. The default value is true.

  • maxAge: defines maximum age (in seconds) for cache to be alive for a pre-flight request. By default, its value is 1800 seconds.

  • allowedMethods: specifies methods (GET, POST,...) to allow when accessing the resource. If we don't use this attribute, it takes the value of @RequestMapping method by default. If we specify methods, default method will be overridden.

  • allowedHeaders: defines the values for Access-Control-Allow-Headers response header. We don't need to list headers if it is one of Cache-Control, Content-Language, Expires, Last-Modified, or Pragma. By default all requested headers are allowed.

  • exposedHeaders: values for Access-Control-Expose-Headers response header. Server uses it to tell the browser about its whitelist headers. By default, an empty exposed header list is used.

    II. Practice

    1. Technology

  • Java 1.8

  • Maven 3.3.9

  • Spring Tool Suite – Version 3.8.4.RELEASE

  • Spring Boot: 1.5.4.RELEASE

    2. Project Overview

    spring-cors-xmlconfig-structure

https://grokonez.com/spring-framework/spring-boot/spring-boot-cors-support-using-xml-config

Spring Boot – CORS Support using XML Config

Top comments (0)