跨源資源共用(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<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.zaixian.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使用RESTful Web服務
下一篇:
Spring Boot國際化