Giter VIP home page Giter VIP logo

spring-guides / gs-rest-service-cors Goto Github PK

View Code? Open in Web Editor NEW
104.0 25.0 122.0 1.22 MB

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/

License: Apache License 2.0

JavaScript 3.67% HTML 5.36% Shell 27.63% Java 63.35%

gs-rest-service-cors's Introduction

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

You can use this pre-initialized project and click Generate to download a ZIP file. This project is configured to fit the examples in this tutorial.

To manually initialize the project:

  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.
Note
You can also fork the project from Github and open it in your IDE or other editor.

Adding the httpclient5 Dependency

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

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

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

The following listing shows the finished pom.xml file:

link:complete/pom.xml[role=include]

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

testImplementation 'org.apache.httpcomponents.client5:httpclient5'

The following listing shows the finished build.gradle file:

link:complete/build.gradle[role=include]

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[role=include]
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[role=include]

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 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[role=include]

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

  • originPatterns

  • methods

  • allowedHeaders

  • exposedHeaders

  • allowCredentials

  • maxAge.

In this example, we allow only http://localhost:9000 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[role=include]
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[role=include]

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[role=include]

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[role=include]

The following listing shows the completed application class:

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

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[role=include]

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[role=include]

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 client running on localhost at port 9000, keep the application running at port 8080 and run the following Maven command in another terminal:

./mvnw spring-boot:run -Dspring-boot.run.jvmArguments='-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 because the service response includes the relevant CORS headers, so the ID and content are rendered into the page:

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

Now, stop the application running at port 9000, keep the application running at port 8080 and run the following Maven command in another terminal:

./mvnw spring-boot:run -Dspring-boot.run.jvmArguments='-Dserver.port=9001'

If you use Gradle, you can use this command:

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

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

The browser will fail the request if the CORS headers are missing (or insufficient for theclient) from the response. No data will be rendered into the DOM.

Here, the browser fails the request and the values are not rendered into the DOM because the CORS headers are missing (or insufficient for the client), since we only allowed cross-origin requests from http://localhost:9000, not http://localhost:9001.

Summary

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

gs-rest-service-cors's People

Contributors

annaddicks avatar buzzardo avatar dsyer avatar gregturn avatar habuma avatar imba-tjd avatar infiniteshi avatar izeye avatar kaklakariada avatar mikfreedman avatar nico769 avatar ptatarski avatar robertmcnees avatar sdeleuze avatar spring-operator avatar yr1404 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gs-rest-service-cors's Issues

Incorrect HTTP client dependency

The line about adding apache http client into gradle.build is not correct. Should be changed by the whole gradle.build file shown below it.

Spring Boot minimal application not running via Windows PowerShell

Is the command to run the minimal Spring Boot application correct in PowerShell environment? Am I missing something? I'm following the guide and it seems it cannot run. Using:

PS C:\Users\mbresciani\Desktop\Spring\Guides\Enabling Cross Origin Requests for a RESTful Web Service> & 'C:\Program Files (x86)\spring-1.1.5.RELEASE\bin\spring.bat' run app.groovy -- --server.port=9000

The immediate answer I see is

'server.port' is not a recognized option

It runs properly in normal command prompt. The gradle bootRun command works even in PowerShell.

Guide is not working as of 2015-11-25

Sorry, guys, checked it out, started to instances
mvn spring-boot:run
mvn spring-boot:run -Dserver.port=9000
followed the tutorial, no Access-Control-Allow-Origin present as a response head, so the demo doesn't work.

Are we missing something in configuration or is @crossorigin annotation broken?

Cors Filter not working on external Tomcat Container

Hi I enabled one of my APIS with @crossorigin annotation.

When I run using spring boot tomcat embedded container it works fine but while deploying the war to an external tomcat container ,it fails.

Any reason why? Morever I am using spring security in my project too

Screen shot is wrong

On the docs, the final 2 screen shots should have the browser pointing to localhost:9000. It is confusing this way.

Update Spring Boot to the latest version

Update the guide to use the most recent Spring Boot version.

Files that require changes are:

initial/build.gradle
initial/pom.xml
complete/build.gradle
complete/pom.xml

Incorrect link to "Consuming a RESTful Web Service with jQuery" in "Enabling Cross Origin Requests for a RESTful Web Service" documentation

The Test the service section of Enabling Cross Origin Requests for a RESTful Web Service has an incorrect link reference to Consuming a RESTful Web Service with jQuery:

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

Steps to reproduce

  • Click the link to "Consuming a RESTful Web Service with jQuery" in the Test the service section

Expected Results

Actual Results

  • Generates a 404 response as the link incorrectly contains rest-service/gs/ in https://spring.io/guides/gs/rest-service/gs/consuming-rest-jquery/

include spring security in example.

I'm about 10 billion kinds of frustrated with the documentation right now. Official and especially this guide. So let's start with this guide. It doesn't include how to make it work with spring security. I know spring security isn't required for CORS, but I think it's probably at least an 80% of the time use case. This still doesn't give me proper CORS headers.

I honestly think this is beyond a problem with just documentation though... but that's a good place to start.

// © Copyright 2024 Caleb Cushing
// SPDX-License-Identifier: AGPL-3.0-or-later

package com.xenoterracide.controller.authn;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.web.exchanges.HttpExchangeRepository;
import org.springframework.boot.actuate.web.exchanges.InMemoryHttpExchangeRepository;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@SpringBootApplication
public class ResourceServer {

  ResourceServer() {}

  public static void main(String[] args) {
    SpringApplication.run(ResourceServer.class, args);
  }

  @Bean
  SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
      .authorizeHttpRequests(auth -> auth.anyRequest().permitAll())
      .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()))
      .cors(Customizer.withDefaults())
      .httpBasic(c -> c.disable())
      .formLogin(f -> f.disable());
    return http.build();
  }

  @Bean
  HttpExchangeRepository httpExchangeRepository() {
    return new InMemoryHttpExchangeRepository();
  }

  @Bean
  CorsConfigurationSource corsConfigurationSource() {
    var cors = new CorsConfiguration();
    cors.addAllowedOrigin("http://localhost:3000");
    cors.addAllowedMethod("*");
    cors.addAllowedHeader("*");
    var source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", cors);
    return source;
  }

  @Bean
  WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
      @Override
      public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/external").allowedOrigins("http://localhost:3000");
      }
    };
  }

  @RestController
  static class OidcTestController {

    private final Logger log = LogManager.getLogger(this.getClass());

    @CrossOrigin(originPatterns = "*")
    @GetMapping("/api/external")
    @NonNull
    String index(@Nullable Authentication details) {
      this.log.info("{}", details);
      var name = details != null ? details.getName() : "world";
      return "Hello, " + name;
    }
  }
}
* Host localhost:8080 was resolved.
* IPv6: ::1
* IPv4: 127.0.0.1
*   Trying [::1]:8080...
* Connected to localhost (::1) port 8080
> GET /api/external HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/8.6.0
> Accept: */*
> 
< HTTP/1.1 200 
< Vary: Origin
< Vary: Access-Control-Request-Method
< Vary: Access-Control-Request-Headers
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 0
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Frame-Options: DENY
< Content-Type: text/plain;charset=UTF-8
< Content-Length: 12
< Date: Fri, 05 Apr 2024 10:13:21 GMT
< 
{ [12 bytes data]
* Connection #0 to host localhost left intact
Hello, world

How do you handle OPTIONS requests with this sample guide?

I'm having trouble after adding authentication, where my OPTIONS preflight is being denied as unauthorized. I'm unsure about where to add this into a Spring Boot app. There seem to be a lot of solutions, but most of them focus on web.xml configurations.

Cors filter ignored

Cors filter annotated with @component gets ignored.
Example works if I de-anotate Filter class and put something like this in web.xml:

<filter>
    <filter-name>Cors Filter</filter-name>
    <filter-class>....SimpleCORSFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>Cors Filter</filter-name>
    <url-pattern>*</url-pattern>
</filter-mapping>

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.