Spring Boot 简明教程

Spring Boot - CORS Support

跨源资源共享 (CORS) 是一种安全概念,允许限制在 Web 浏览器中实现的资源。它可以防止 JavaScript 代码针对不同的源创建或使用请求。

例如,如果你的 Web 应用程序正在 8080 端口运行,并且通过使用 JavaScript 尝试从 9090 端口使用 RESTful Web 服务。在这种情况下,你将在 Web 浏览器上遇到跨源资源共享安全问题。

需要两个条件来处理此问题 −

  1. RESTful Web 服务应该支持跨源资源共享。

  2. RESTful Web 服务应用程序应该允许从 8080 端口访问 API。

在本章中,我们将详细了解如何为 RESTful Web 服务应用程序启用跨源请求。

Enable CORS in Controller Method

我们需要通过 @CrossOrigin 为控制器方法添加注解来设置 RESTful Web 服务的来源。此 @CrossOrigin 注解支持特定的 REST API,而并非整个应用程序。

@RequestMapping(value = "/products")
@CrossOrigin(origins = "http://localhost:8080")

public ResponseEntity<Object> getProduct() {
   return null;
}

Global CORS Configuration

我们需要定义所示的 @Bean 配置,以将 CORS 配置支持全局应用于你的 Spring Boot 应用程序。

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

在 Spring Boot 主应用程序中全局设置 CORS 配置的代码如下所示。

package com.tutorialspoint.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@SpringBootApplication
public class DemoApplication {
   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }
   @Bean
   public WebMvcConfigurer corsConfigurer() {
      return new WebMvcConfigurerAdapter() {
         @Override
         public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/products").allowedOrigins("http://localhost:8080");
         }
      };
   }
}

现在,你可以创建一个在 8080 端口上运行的 Spring Boot Web 应用程序,以及可以在 9090 端口上运行的你的 RESTful 服务应用程序。有关 RESTful Web 服务实现的更多详细信息,你可以参阅本教程中题为 Consuming RESTful Web Services 的章节。