Spring?Boot3?跨域配置?Cors的方式
什么是CORS?
CORS,全稱是“跨源資源共享”(Cross-Origin Resource Sharing),是一種Web應(yīng)用程序的安全機(jī)制,用于控制不同源的資源之間的交互。
在Web應(yīng)用程序中,CORS定義了一種機(jī)制,通過該機(jī)制,瀏覽器能夠限制哪些外部網(wǎng)頁可以訪問來自不同源的資源。源由協(xié)議、域名和端口組成。當(dāng)一個網(wǎng)頁請求另一個網(wǎng)頁上的資源時,瀏覽器會檢查請求是否符合CORS規(guī)范,以確定是否允許該請求。
CORS的工作原理是:當(dāng)瀏覽器發(fā)送一個跨域請求時,它會附加一些額外的頭部信息到請求中,這些頭部信息包含了關(guān)于請求的來源和目的的信息。服務(wù)器可以檢查這些頭部信息并決定是否允許該請求。如果服務(wù)器允許請求,它會返回一個響應(yīng),其中包含一個名為“Access-Control-Allow-Origin”的頭部信息,該信息指定了哪些源可以訪問該資源。瀏覽器會檢查返回的“Access-Control-Allow-Origin”頭部信息,以確定是否允許該跨域請求。
通過使用CORS,開發(fā)人員可以控制哪些外部網(wǎng)頁可以訪問他們的資源,從而提高應(yīng)用程序的安全性。
Spring Boot 如何配置CORS?
Spring Boot對于跨域請求的支持可以通過兩種配置方式來實(shí)現(xiàn):
- 注解配置:可以使用@CrossOrigin注解來啟用CORS。例如,在需要支持跨域請求的方法上添加@CrossOrigin注解,并配置好origins和maxAge等參數(shù)。
- 全局配置:可以通過實(shí)現(xiàn)WebMvcConfigurer接口并注冊一個WebMvcConfigurer bean來配置CORS的全局設(shè)置。在實(shí)現(xiàn)類中覆蓋addCorsMappings方法,通過CorsRegistry對象添加映射規(guī)則。默認(rèn)情況下,所有方法都支持跨域,并且GET、POST和HEAD請求是被允許的。如果需要自定義,可以配置CorsRegistry對象來指定允許的域名、端口和請求方法等。
- 過濾器配置:可以通過
CorsFilter
bean來配置CORS的過濾器。這種方式可以更加靈活地控制CORS的配置,例如只允許特定的域名進(jìn)行跨域訪問等。
前端代碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script> </head> <body> <script> $.ajax({ url: 'http://localhost:8080/hello', type: 'GET', //xhrFields: { withCredentials: true }, //開啟認(rèn)證 success: function (data) { console.log(data) } }) </script> </body> </html>
注解配置
@CrossOrigin
是 Spring Framework 中的一個注解,用于處理跨域請求。當(dāng)一個前端頁面嘗試從不同的源(域名、端口或協(xié)議)請求數(shù)據(jù)時,瀏覽器的同源策略會阻止這種請求,以防止?jié)撛诘陌踩珕栴}。然而,在某些情況下,你可能希望允許跨域請求,這時就可以使用 @CrossOrigin
注解。
添加CorssOrigin注解
package com.mcode.springbootcorsdemo.controller; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; /** * ClassName: HelloController * Package: com.mcode.springbootcorsdemo.controller * Description: * * @Author: robin * @Version: v1.0 */ @RestController public class HelloController { @CrossOrigin(value = "http://127.0.0.1:5500",allowedHeaders = "*",allowCredentials = "true") @GetMapping("/hello") public String hello(){ return "Hello"; } }
屬性:
@CrossOrigin
注解有幾個屬性,允許你更精細(xì)地控制跨域行為:
* origins: 允許的源列表,可以是域名、IP 或其他標(biāo)識符。多個源可以使用逗號分隔。 * methods: 允許的 HTTP 方法列表。例如,只允許 GET 請求。 * allowedHeaders: 允許的請求頭列表。默認(rèn)情況下,允許所有請求頭。 * allowCredentials:是否允許配置;值為true、false的字符串 * maxAge: 預(yù)檢請求的緩存時間(以秒為單位)。默認(rèn)是 86400 秒(24小時)。這些屬性可以根據(jù)需要進(jìn)行組合和配置。
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by FernFlower decompiler) // package org.springframework.web.bind.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.core.annotation.AliasFor; @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface CrossOrigin { @AliasFor("origins") String[] value() default {}; @AliasFor("value") String[] origins() default {}; String[] originPatterns() default {}; String[] allowedHeaders() default {}; String[] exposedHeaders() default {}; RequestMethod[] methods() default {}; String allowCredentials() default ""; long maxAge() default -1L; }
全局配置
addCorsMappings
是 Spring Boot 中用于配置跨域請求的方法。它允許你指定哪些路徑的請求需要進(jìn)行跨域處理,以及如何處理這些請求。
在 addCorsMappings
方法中,你可以使用 addMapping
方法來指定需要跨域處理的請求路徑。例如:
package com.mcode.springbootcorsdemo.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * ClassName: MyWebMvcConfigurer * Package: com.mcode.springbootcorsdemo.config * Description: * * @Author: robin * @Version: v1.0 */ @Configuration public class MyWebMvcConfigurer implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") // 允許所有請求路徑跨域訪問 .allowCredentials(true) // 是否攜帶Cookie,默認(rèn)false .allowedHeaders("*") // 允許的請求頭類型 .maxAge(3600) // 預(yù)檢請求的緩存時間(單位:秒) .allowedMethods("*") // 允許的請求方法類型 .allowedOrigins("http://127.0.0.1:5500"); // 允許哪些域名進(jìn)行跨域訪問 } }
過濾器配置
在Spring Boot中,CorsFilter用于處理跨域請求。它是一個過濾器,用于在Spring應(yīng)用程序中啟用CORS(跨源資源共享)支持。
package com.mcode.springbootcorsdemo.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; /** * ClassName: CorsConfig * Package: com.mcode.springbootcorsdemo.config * Description: * * @Author: robin * @Version: v1.0 */ @Configuration public class CorsConfig { @Bean public CorsFilter corsFilter(){ CorsConfiguration config = new CorsConfiguration(); config.addAllowedHeader("*"); config.addAllowedMethod("*"); config.addAllowedOrigin("http://127.0.0.1:5500"); config.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**",config); return new CorsFilter(source); } }
注意事項(xiàng)
當(dāng)我們沒有配置跨域的時候會提示:
Access to XMLHttpRequest at 'http://localhost:8080/hello' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
當(dāng)我們開啟withCredentials:true
的時候沒有配置allowCredentials為true
會提示:
Access to XMLHttpRequest at 'http://localhost:8080/hello' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
當(dāng)我們在后端配置了allowCredentials(true)
那么就不能配置allowedOrigins("*")
,必須指定來源
jakarta.servlet.ServletException: Request processing failed: java.lang.IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot contain the special value "*" since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.
到此這篇關(guān)于Spring Boot3 跨域配置 Cors的文章就介紹到這了,更多相關(guān)Spring Boot3 跨域配置 Cors內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot實(shí)現(xiàn)多個ApplicationRunner時部分接口未執(zhí)行問題
這篇文章主要介紹了SpringBoot實(shí)現(xiàn)多個ApplicationRunner時部分接口未執(zhí)行問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05idea打開項(xiàng)目沒有項(xiàng)目目錄問題及解決
這篇文章主要介紹了idea打開項(xiàng)目沒有項(xiàng)目目錄問題及解決,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-06-06Mybatis Generator逆向工程的使用詳細(xì)教程
這篇文章主要介紹了Mybatis Generator逆向工程的使用詳細(xì)教程,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-06-06spring boot自定義配置時在yml文件輸入有提示問題及解決方案
自定義一個配置類,然后在yml文件具體配置值時,一般不會有提示,今天小編給大家分享spring boot自定義配置時在yml文件輸入有提示問題,感興趣的朋友一起看看吧2023-10-10