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

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

需要两个要求来处理这个问题 –

  • RESTful Web 服务应该支持跨源资源共享。
  • RESTful Web 服务应用程序应允许从 8080 端口访问 API。

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

在控制器方法中启用 CORS

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

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

public ResponseEntity 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.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 Web 服务应用程序。关于 RESTful Web Service 的更多实现细节,可以参考本教程“使用 RESTful Web 服务”一章。

 

Spring Boot CORS 支持 推荐

Python深度学习 教程03 – Python人工神经网络

影院院线