SHoar / gs-rest-service-cors

Enabling Cross Origin Requests for a RESTful Web Service :: Learn how to create a RESTful web service with Spring that support Cross-Origin Resource Sharing (CORS).

Home Page:https://spring.io/guides/gs/rest-service-cors/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

This guide walks you through the process of creating a “Hello, World” RESTful web service with Spring that includes headers for Cross-Origin Resource Sharing (CORS) in the response. You can find more information about Spring CORS support in this blog post.

What You Will Build

You will build a service that accepts HTTP GET requests at http://localhost:8080/greeting and responds with a JSON representation of a greeting, as the following listing shows:

{"id":1,"content":"Hello, World!"}

You can customize the greeting with an optional name parameter in the query string, as the following listing shows:

http://localhost:8080/greeting?name=User

The name parameter value overrides the default value of World and is reflected in the response, as the following listing shows:

{"id":1,"content":"Hello, User!"}

This service differs slightly from the one described in Building a RESTful Web Service, in that it uses Spring Framework CORS support to add the relevant CORS response headers.

Starting with Spring Initializr

If you use Maven, visit the Spring Initializr to generate a new project with the required dependency (Spring Web).

The following listing shows the pom.xml file that is created when you choose Maven:

link:initial/pom.xml[]

If you use Gradle, visit the Spring Initializr to generate a new project with the required dependency (Spring Web).

The following listing shows the build.gradle file that is created when you choose Gradle:

link:initial/build.gradle[]

Manual Initialization (optional)

If you want to initialize the project manually rather than use the links shown earlier, follow the steps given below:

  1. Navigate to https://start.spring.io. This service pulls in all the dependencies you need for an application and does most of the setup for you.

  2. Choose either Gradle or Maven and the language you want to use. This guide assumes that you chose Java.

  3. Click Dependencies and select Spring Web.

  4. Click Generate.

  5. Download the resulting ZIP file, which is an archive of a web application that is configured with your choices.

Note
If your IDE has the Spring Initializr integration, you can complete this process from your IDE.

Adding the httpclient Dependency

The tests (in complete/src/test/java/com/example/restservicecors/GreetingIntegrationTests.java) require the Apache httpclient library.

To add the Apache httpclient library to Maven, add the following dependency:

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <scope>test</scope>
</dependency>

The following listing shows the finished pom.xml file:

link:complete/pom.xml[]

To add the Apache httpclient library to Gradle, add the following dependency:

testImplementation 'org.apache.httpcomponents:httpclient'

The following listing shows the finished build.gradle file:

link:complete/build.gradle[]

Create a Resource Representation Class

Now that you have set up the project and build system, you can create your web service.

Begin the process by thinking about service interactions.

The service will handle GET requests to /greeting, optionally with a name parameter in the query string. The GET request should return a 200 OK response with JSON in the body to represent a greeting. It should resemble the following listing:

{
    "id": 1,
    "content": "Hello, World!"
}

The id field is a unique identifier for the greeting, and content is the textual representation of the greeting.

To model the greeting representation, create a resource representation class. Provide a plain old Java object with fields, constructors, and accessors for the id and content data, as the following listing (from src/main/java/com/example/restservicecors/Greeting.java) shows:

link:complete/src/main/java/com/example/restservicecors/Greeting.java[]
Note
Spring uses the Jackson JSON library to automatically marshal instances of type Greeting into JSON.

Create a Resource Controller

In Spring’s approach to building RESTful web services, HTTP requests are handled by a controller. These components are easily identified by the @Controller annotation, and the GreetingController shown in the following listing (from src/main/java/com/example/restservicecors/GreetingController.java) handles GET requests for /greeting by returning a new instance of the Greeting class:

link:complete/src/main/java/com/example/restservicecors/GreetingController.java[]

This controller is concise and simple, but there is plenty going on under the hood. We break it down step by step.

The @RequestMapping annotation ensures that HTTP requests to /greeting are mapped to the greeting() method.

Note
The preceding example uses the @GetMapping annotation, which acts as a shortcut for @RequestMapping(method = RequestMethod.GET). We use GET in this case because it is convenient for testing. Spring will still reject a GET request where the origin doesn’t match the CORS configuration. The browser is not required to send a CORS preflight request, but we could use @PostMapping and accept some JSON in the body if we wanted to trigger a pre-flight check.

@RequestParam binds the value of the name query string parameter into the name parameter of the greeting() method. This query string parameter is not required. If it is absent in the request, the defaultValue of World is used.

The implementation of the method body creates and returns a new Greeting object, with the value of the id attribute based on the next value from the counter and the value of the content based on the query parameter or the default value. It also formats the given name by using the greeting template.

A key difference between a traditional MVC controller and the RESTful web service controller shown earlier is the way that the HTTP response body is created. Rather than relying on a view technology to perform server-side rendering of the greeting data to HTML, this RESTful web service controller populates and returns a Greeting object. The object data is written directly to the HTTP response as JSON.

To accomplish this, the {RestController}[@RestController] annotation assumes that every method inherits the @ResponseBody semantics by default. Therefore, a returned object data is inserted directly into the response body.

Thanks to Spring’s HTTP message converter support, the Greeting object is naturally converted to JSON. Because Jackson is on the classpath, Spring’s MappingJackson2HttpMessageConverter is automatically chosen to convert the Greeting instance to JSON.

Enabling CORS

You can enable cross-origin resource sharing (CORS) from either in individual controllers or globally. The following topics describe how to do so:

Controller Method CORS Configuration

So that the RESTful web service will include CORS access control headers in its response, you have to add a @CrossOrigin annotation to the handler method, as the following listing (from src/main/java/com/example/restservicecors/GreetingController.java) shows:

link:complete/src/main/java/com/example/restservicecors/GreetingController.java[]

This @CrossOrigin annotation enables cross-origin resource sharing only for this specific method. By default, its allows all origins, all headers, and the HTTP methods specified in the @RequestMapping annotation. Also, a maxAge of 30 minutes is used. You can customize this behavior by specifying the value of one of the following annotation attributes:

  • origins

  • methods

  • allowedHeaders

  • exposedHeaders

  • allowCredentials

  • maxAge.

In this example, we allow only http://localhost:8080 to send cross-origin requests.

Note
You can also add the @CrossOrigin annotation at the controller class level as well, to enable CORS on all handler methods of this class.

Global CORS configuration

In addition (or as an alternative) to fine-grained annotation-based configuration, you can define some global CORS configuration as well. This is similar to using a Filter but can be declared within Spring MVC and combined with fine-grained @CrossOrigin configuration. By default, all origins and GET, HEAD, and POST methods are allowed.

The following listing (from src/main/java/com/example/restservicecors/GreetingController.java) shows the greetingWithJavaconfig method in the GreetingController class:

link:complete/src/main/java/com/example/restservicecors/GreetingController.java[]
Note
The difference between the greetingWithJavaconfig method and the greeting method (used in the controller-level CORS configuration) is the route (/greeting-javaconfig rather than /greeting) and the presence of the @CrossOrigin origin.

The following listing (from src/main/java/com/example/restservicecors/RestServiceCorsApplication.java) shows how to add CORS mapping in the application class:

link:complete/src/main/java/com/example/restservicecors/RestServiceCorsApplication.java[]

You can easily change any properties (such as allowedOrigins in the example), as well as apply this CORS configuration to a specific path pattern.

Tip
You can combine global- and controller-level CORS configuration.

Creating the Application Class

The Spring Initializr creates a bare-bones application class for you. The following listing (from initial/src/main/java/com/example/restservicecors/RestServiceCorsApplication.java) shows that initial class:

link:initial/src/main/java/com/example/restservicecors/RestServiceCorsApplication.java[]

You need to add a method to configure how to handle cross-origin resource sharing. The following listing (from complete/src/main/java/com/example/restservicecors/RestServiceCorsApplication.java) shows how to do so:

link:complete/src/main/java/com/example/restservicecors/RestServiceCorsApplication.java[]

The following listing shows the completed application class:

link:complete/src/main/java/com/example/restservicecors/RestServiceCorsApplication.java[]

Logging output is displayed. The service should be up and running within a few seconds.

Test the service

Now that the service is up, visit http://localhost:8080/greeting in your browser where you should see:

{"id":1,"content":"Hello, World!"}

Provide a name query string parameter by visiting http://localhost:8080/greeting?name=User. The value of the content attribute changes from Hello, World! to Hello User!, as the following listing shows:

{"id":2,"content":"Hello, User!"}

This change demonstrates that the @RequestParam arrangement in GreetingController works as expected. The name parameter has been given a default value of World but can always be explicitly overridden through the query string.

Also, the id attribute has changed from 1 to 2. This proves that you are working against the same GreetingController instance across multiple requests and that its counter field is being incremented on each call, as expected.

Now you can test that the CORS headers are in place and allow a Javascript client from another origin to access the service. To do so, you need to create a Javascript client to consume the service. The following listing shows such a client:

First, create a simple Javascript file named hello.js (from complete/public/hello.js) with the following content:

link:complete/public/hello.js[]

This script uses jQuery to consume the REST service at http://localhost:8080/greeting. It is loaded by index.html, as the following listing (from complete/public/index.html) shows:

link:complete/public/index.html[]
Note
This is essentially the REST client created in Consuming a RESTful Web Service with jQuery, modified slightly to consume the service when it runs on localhost at port 8080. See that guide for more details on how this client was developed.

To start the client running on localhost at port 8080, run the following Maven command:

./mvnw spring-boot:run

If you use Gradle, you can use this command:

./gradlew bootRun

Once the app starts, open http://localhost:8080 in your browser, where you should see the following:

The browser will fail the request if the CORS headers are missing from the response. No data will be rendered into the DOM.

To test the CORS behaviour, you need to start the client from another server or port. Doing so not only avoids a collision between the two applications but also ensures that the client code is served from a different origin than the service. To start the app running on localhost at port 9000 (as well as the one that is already running on port 8080), run the following Maven command:

./mvnw spring-boot:run -Dserver.port=9000

If you use Gradle, you can use this command:

./gradlew bootRun --args="--server.port=9000"

Once the app starts, open http://localhost:9000 in your browser, where you should see the following:

Model data retrieved from the REST service is rendered into the DOM if the proper CORS headers are in the response.

If the service response includes the CORS headers, then the ID and content are rendered into the page. But if the CORS headers are missing (or insufficient for the client), the browser fails the request and the values are not rendered into the DOM.

Summary

Congratulations! You have just developed a RESTful web service that includes Cross-Origin Resource Sharing with Spring.

About

Enabling Cross Origin Requests for a RESTful Web Service :: Learn how to create a RESTful web service with Spring that support Cross-Origin Resource Sharing (CORS).

https://spring.io/guides/gs/rest-service-cors/

License:Apache License 2.0


Languages

Language:Java 63.5%Language:Shell 27.5%Language:HTML 5.4%Language:JavaScript 3.7%