Spring?Boot3?跨域配置?Cors的方式
什么是CORS?
CORS,全稱是“跨源資源共享”(Cross-Origin Resource Sharing),是一種Web應(yīng)用程序的安全機(jī)制,用于控制不同源的資源之間的交互。
在Web應(yīng)用程序中,CORS定義了一種機(jī)制,通過該機(jī)制,瀏覽器能夠限制哪些外部網(wǎng)頁可以訪問來自不同源的資源。源由協(xié)議、域名和端口組成。當(dāng)一個(gè)網(wǎng)頁請(qǐng)求另一個(gè)網(wǎng)頁上的資源時(shí),瀏覽器會(huì)檢查請(qǐng)求是否符合CORS規(guī)范,以確定是否允許該請(qǐng)求。
CORS的工作原理是:當(dāng)瀏覽器發(fā)送一個(gè)跨域請(qǐng)求時(shí),它會(huì)附加一些額外的頭部信息到請(qǐng)求中,這些頭部信息包含了關(guān)于請(qǐng)求的來源和目的的信息。服務(wù)器可以檢查這些頭部信息并決定是否允許該請(qǐng)求。如果服務(wù)器允許請(qǐng)求,它會(huì)返回一個(gè)響應(yīng),其中包含一個(gè)名為“Access-Control-Allow-Origin”的頭部信息,該信息指定了哪些源可以訪問該資源。瀏覽器會(huì)檢查返回的“Access-Control-Allow-Origin”頭部信息,以確定是否允許該跨域請(qǐng)求。
通過使用CORS,開發(fā)人員可以控制哪些外部網(wǎng)頁可以訪問他們的資源,從而提高應(yīng)用程序的安全性。
Spring Boot 如何配置CORS?
Spring Boot對(duì)于跨域請(qǐng)求的支持可以通過兩種配置方式來實(shí)現(xiàn):
- 注解配置:可以使用@CrossOrigin注解來啟用CORS。例如,在需要支持跨域請(qǐng)求的方法上添加@CrossOrigin注解,并配置好origins和maxAge等參數(shù)。
- 全局配置:可以通過實(shí)現(xiàn)WebMvcConfigurer接口并注冊(cè)一個(gè)WebMvcConfigurer bean來配置CORS的全局設(shè)置。在實(shí)現(xiàn)類中覆蓋addCorsMappings方法,通過CorsRegistry對(duì)象添加映射規(guī)則。默認(rèn)情況下,所有方法都支持跨域,并且GET、POST和HEAD請(qǐng)求是被允許的。如果需要自定義,可以配置CorsRegistry對(duì)象來指定允許的域名、端口和請(qǐng)求方法等。
- 過濾器配置:可以通過
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 中的一個(gè)注解,用于處理跨域請(qǐng)求。當(dāng)一個(gè)前端頁面嘗試從不同的源(域名、端口或協(xié)議)請(qǐng)求數(shù)據(jù)時(shí),瀏覽器的同源策略會(huì)阻止這種請(qǐng)求,以防止?jié)撛诘陌踩珕栴}。然而,在某些情況下,你可能希望允許跨域請(qǐng)求,這時(shí)就可以使用 @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
注解有幾個(gè)屬性,允許你更精細(xì)地控制跨域行為:
* origins: 允許的源列表,可以是域名、IP 或其他標(biāo)識(shí)符。多個(gè)源可以使用逗號(hào)分隔。 * methods: 允許的 HTTP 方法列表。例如,只允許 GET 請(qǐng)求。 * allowedHeaders: 允許的請(qǐng)求頭列表。默認(rèn)情況下,允許所有請(qǐng)求頭。 * allowCredentials:是否允許配置;值為true、false的字符串 * maxAge: 預(yù)檢請(qǐng)求的緩存時(shí)間(以秒為單位)。默認(rèn)是 86400 秒(24小時(shí))。這些屬性可以根據(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 中用于配置跨域請(qǐng)求的方法。它允許你指定哪些路徑的請(qǐng)求需要進(jìn)行跨域處理,以及如何處理這些請(qǐng)求。
在 addCorsMappings
方法中,你可以使用 addMapping
方法來指定需要跨域處理的請(qǐng)求路徑。例如:
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("/**") // 允許所有請(qǐng)求路徑跨域訪問 .allowCredentials(true) // 是否攜帶Cookie,默認(rèn)false .allowedHeaders("*") // 允許的請(qǐng)求頭類型 .maxAge(3600) // 預(yù)檢請(qǐng)求的緩存時(shí)間(單位:秒) .allowedMethods("*") // 允許的請(qǐng)求方法類型 .allowedOrigins("http://127.0.0.1:5500"); // 允許哪些域名進(jìn)行跨域訪問 } }
過濾器配置
在Spring Boot中,CorsFilter用于處理跨域請(qǐng)求。它是一個(gè)過濾器,用于在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)我們沒有配置跨域的時(shí)候會(huì)提示:
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
的時(shí)候沒有配置allowCredentials為true
會(huì)提示:
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)我們?cè)诤蠖伺渲昧?code>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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 關(guān)于springboot2.4跨域配置問題
- Springboot 跨域配置無效及接口訪問報(bào)錯(cuò)的解決方法
- Springboot前后端分離項(xiàng)目配置跨域?qū)崿F(xiàn)過程解析
- springboot配置允許跨域訪問代碼實(shí)例
- Springboot處理配置CORS跨域請(qǐng)求時(shí)碰到的坑
- 基于SpringBoot解決CORS跨域的問題(@CrossOrigin)
- Springboot處理CORS跨域請(qǐng)求的三種方法
- 詳解springboot設(shè)置cors跨域請(qǐng)求的兩種方式
- vue+springboot實(shí)現(xiàn)項(xiàng)目的CORS跨域請(qǐng)求
相關(guān)文章
SpringBoot實(shí)現(xiàn)多個(gè)ApplicationRunner時(shí)部分接口未執(zhí)行問題
這篇文章主要介紹了SpringBoot實(shí)現(xiàn)多個(gè)ApplicationRunner時(shí)部分接口未執(zhí)行問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-05-05idea打開項(xiàng)目沒有項(xiàng)目目錄問題及解決
這篇文章主要介紹了idea打開項(xiàng)目沒有項(xiàng)目目錄問題及解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06Mybatis Generator逆向工程的使用詳細(xì)教程
這篇文章主要介紹了Mybatis Generator逆向工程的使用詳細(xì)教程,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-06-06spring boot自定義配置時(shí)在yml文件輸入有提示問題及解決方案
自定義一個(gè)配置類,然后在yml文件具體配置值時(shí),一般不會(huì)有提示,今天小編給大家分享spring boot自定義配置時(shí)在yml文件輸入有提示問題,感興趣的朋友一起看看吧2023-10-10