Spring Boot CORS支持
跨源資源共享(CORS)是一種安全概念,用於限制Web瀏覽器中實現的資源。 它可以防止JavaScript代碼產生或消耗針對不同來源的請求。
例如,Web應用程序在8080端口上運行,並且使用JavaScript嘗試從9090端口使用RESTful Web服務。在這種情況下,在Web瀏覽器上將面臨跨源資源共享安全問題。
處理此問題需要兩個要求 -
- RESTful Web服務應該支持跨源資源共享。
- RESTful Web服務應用程序應允許從8080端口訪問API。
在本章中,將詳細瞭解如何爲RESTful Web服務應用程序啓用跨源請求。
在控制器方法中啓用CORS
需要通過對控制器方法使用[@CrossOrigin](https://github.com/CrossOrigin "@CrossOrigin")
註解來設置RESTful Web服務的起源。 [@CrossOrigin](https://github.com/CrossOrigin "@CrossOrigin")
注源支持特定的REST API,而不支持整個應用程序。
@RequestMapping(value = "/products")
@CrossOrigin(origins = "http://localhost:8080")
public ResponseEntity<Object> getProduct() {
return null;
}
全局CORS配置
需要定義顯示的[@Bean](https://github.com/Bean "@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.yiibai.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服務」一章。
0 條評論,你可以發表評論,我們會進行改進
