目录

Spring Boot - CORS Support

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

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

处理此问题需要两个要求 -

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

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

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

在Controller方法中启用CORS

我们需要通过对控制器方法使用@CrossOrigin注释来设置RESTful Web服务的起源。 @CrossOrigin注释支持特定的REST API,而不支持整个应用程序。

@RequestMapping(value = "/products")
@CrossOrigin(origins = "http://localhost:8080")
public ResponseEntity<Object> getProduct() {
   return null;
}

全局CORS配置

我们需要定义显示的@Bean配置,以便为您的Spring Boot应用程序全局设置CORS配置支持。

@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.iowiki.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 Web服务应用程序。 有关RESTful Web Service实现的更多详细信息,请参阅本教程的“使用Consuming RESTful Web Services ”一章。

↑回到顶部↑
WIKI教程 @2018