最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot+Vue跨域配置(CORS)問(wèn)題得解決過(guò)程

 更新時(shí)間:2024年08月14日 08:57:33   作者:繁依Fanyi  
在使用 Spring Boot 和 Vue 開(kāi)發(fā)前后端分離的項(xiàng)目時(shí),跨域資源共享(CORS)問(wèn)題是一個(gè)常見(jiàn)的挑戰(zhàn),接下來(lái),我將分享我是如何一步步解決這個(gè)問(wèn)題的,包括中間的一些試錯(cuò)過(guò)程,希望能夠幫助到正在經(jīng)歷類(lèi)似問(wèn)題的你

1. 問(wèn)題描述

在我們開(kāi)發(fā)的過(guò)程中,Vue 前端需要與 Spring Boot 后端通信。如果后端沒(méi)有正確配置 CORS,瀏覽器會(huì)進(jìn)行跨域檢查并阻止請(qǐng)求,報(bào)錯(cuò)信息如下:

Access to XMLHttpRequest at 'http://localhost:8789/auth/register' from origin 'http://localhost:8081' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

2. 解決方案概述

為了解決這個(gè)問(wèn)題,我們需要在 Spring Boot 應(yīng)用中配置 CORS。這個(gè)過(guò)程包括創(chuàng)建一個(gè) CORS 配置類(lèi),并在 Spring Security 配置類(lèi)中應(yīng)用這個(gè)配置。

3. 試錯(cuò)過(guò)程

3.1 初步嘗試:簡(jiǎn)單的 CORS 配置

我首先嘗試在 Spring Boot 中添加一個(gè)簡(jiǎn)單的 CORS 配置類(lèi):

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;

@Configuration
public class CorsConfig {

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.addAllowedOrigin("*");
        configuration.addAllowedMethod("*");
        configuration.addAllowedHeader("*");
        configuration.setAllowCredentials(true);
        configuration.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

然后,在 WebSecurityConfig 中應(yīng)用這個(gè)配置:

http.cors().configurationSource(corsConfigurationSource());

結(jié)果,前端依舊報(bào)錯(cuò),沒(méi)有任何變化。

3.2 細(xì)化 Security 配置

我接著嘗試在 WebSecurityConfig 中進(jìn)一步細(xì)化 CORS 配置:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().configurationSource(corsConfigurationSource())
            .and().csrf().disable();
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.addAllowedOrigin("*");
        configuration.addAllowedMethod("*");
        configuration.addAllowedHeader("*");
        configuration.setAllowCredentials(true);
        configuration.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

然而,前端還是無(wú)法正常發(fā)起跨域請(qǐng)求,這讓我非常困惑。

3.3 嘗試代理配置

為了確保開(kāi)發(fā)過(guò)程中跨域請(qǐng)求能正確代理到后端,我在 Vue 項(xiàng)目中添加了代理配置:

首先,確保項(xiàng)目使用 vue-cli 創(chuàng)建,并確保有 vue.config.js 文件。然后添加如下代理配置:

let proxyObj = {};
proxyObj['/'] = {
    target: 'http://localhost:8789/',
    changeOrigin: true,
    pathRewrite: {
        '^/': ''
    }
}

module.exports = {
    devServer: {
        open: true,
        host: 'localhost',
        port: 8081,
        proxy: proxyObj,
    },
}

這種配置可以使前端的跨域請(qǐng)求通過(guò)代理轉(zhuǎn)發(fā)到后端。不過(guò),這只是開(kāi)發(fā)環(huán)境下的解決方案,并沒(méi)有真正解決后端的 CORS 配置問(wèn)題。

3.4 最終解決方案:完善的 CORS 和 Security 配置

經(jīng)過(guò)幾次嘗試和查閱資料后,我最終找到了一個(gè)有效的解決方案,結(jié)合之前的經(jīng)驗(yàn),創(chuàng)建了一個(gè)完善的 CORS 和 Security 配置。

CorsConfig.java

package cn.techfanyi.fanyi.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;

@Configuration
public class CorsConfig {

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration corsConfig = new CorsConfiguration();
        corsConfig.addAllowedOriginPattern("*"); // 允許任何源
        corsConfig.addAllowedMethod("*"); // 允許任何HTTP方法
        corsConfig.addAllowedHeader("*"); // 允許任何HTTP頭
        corsConfig.setAllowCredentials(true); // 允許證書(shū)(cookies)
        corsConfig.setMaxAge(3600L); // 預(yù)檢請(qǐng)求的緩存時(shí)間(秒)

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfig); // 對(duì)所有路徑應(yīng)用這個(gè)配置
        return source;
    }
}

WebSecurityConfig.java

package cn.techfanyi.fanyi.config;

import cn.techfanyi.fanyi.filter.JwtRequestFilter;
import cn.techfanyi.fanyi.security.CustomAccessDeniedHandler;
import cn.techfanyi.fanyi.security.CustomAuthenticationEntryPoint;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig {

    private final JwtRequestFilter jwtRequestFilter;
    private final CustomAuthenticationEntryPoint customAuthenticationEntryPoint;
    private final CustomAccessDeniedHandler customAccessDeniedHandler;

    public WebSecurityConfig(JwtRequestFilter jwtRequestFilter,
                          CustomAuthenticationEntryPoint customAuthenticationEntryPoint,
                          CustomAccessDeniedHandler customAccessDeniedHandler) {
        this.jwtRequestFilter = jwtRequestFilter;
        this.customAuthenticationEntryPoint = customAuthenticationEntryPoint;
        this.customAccessDeniedHandler = customAccessDeniedHandler;
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws  Exception {
        http.csrf().disable()
                .cors(cors -> cors.configurationSource(corsConfigurationSource()))
                .authorizeRequests(authorizedRequests ->
                        authorizedRequests.requestMatchers("/**").permitAll()
                                .anyRequest().authenticated())
                .exceptionHandling(exceptionHandling ->
                        exceptionHandling.authenticationEntryPoint(customAuthenticationEntryPoint)
                                .accessDeniedHandler(customAccessDeniedHandler))
                .sessionManagement(sessionManagement ->
                        sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

    private CorsConfigurationSource corsConfigurationSource() {
        return new CorsConfig().corsConfigurationSource();
    }
}

但是又出現(xiàn)以下錯(cuò)誤:

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.

這個(gè)錯(cuò)誤信息表明,在 Spring Boot 的 CORS 配置中,當(dāng) allowCredentials 設(shè)置為 true 時(shí),allowedOrigins 不能包含特殊值 "*", 因?yàn)闉g覽器不允許在 Access-Control-Allow-Origin 響應(yīng)頭中設(shè)置 "*", 同時(shí)還允許憑證(如 cookies)。此時(shí)應(yīng)該使用 allowedOriginPatterns 來(lái)代替 allowedOrigins。

具體的錯(cuò)誤原因如下:

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.

這意味著當(dāng) allowCredentials 設(shè)置為 true 時(shí),不能將 allowedOrigins 設(shè)置為 "*", 因?yàn)樗荒茉陧憫?yīng)頭中設(shè)置 Access-Control-Allow-Origin 為 "*", 同時(shí)還允許憑證。為了解決這個(gè)問(wèn)題,您需要將 allowedOrigins 改為使用 allowedOriginPatterns。

修改 CorsConfigurationSource 如下:

 @Bean
 public CorsConfigurationSource corsConfigurationSource() {
     CorsConfiguration corsConfig = new CorsConfiguration();
     corsConfig.addAllowedOriginPattern("*"); // 使用 allowedOriginPatterns 代替 allowedOrigins
     corsConfig.addAllowedMethod("*"); 
     corsConfig.addAllowedHeader("*");
     corsConfig.setAllowCredentials(true);
     corsConfig.setMaxAge(3600L);

     UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
     source.registerCorsConfiguration("/**", corsConfig);
     return source;
 }

通過(guò)以上配置,可以解決 allowCredentials 和 allowedOrigins 中 "*" 沖突的問(wèn)題,使得您的 Spring Boot 應(yīng)用可以正確處理跨域請(qǐng)求。

通過(guò)以上配置,前端請(qǐng)求終于可以成功與后端通信,CORS 問(wèn)題不再出現(xiàn)。

4. 為什么要這樣修改

在 Spring Security 6 中,安全配置的方式有所變化。與之前版本相比,Spring Security 6 更加靈活和模塊化。為了使 CORS 配置生效,我們需要:

  1. 明確指定 CORS 配置源:在 securityFilterChain 方法中,通過(guò) http.cors(cors -> cors.configurationSource(corsConfigurationSource())) 明確指定使用我們自定義的 CorsConfigurationSource
  2. 禁用默認(rèn)的 CSRF 保護(hù):對(duì)于大多數(shù) API 項(xiàng)目,特別是無(wú)狀態(tài)的 RESTful 服務(wù),禁用 CSRF 是常見(jiàn)的做法。通過(guò) http.csrf().disable() 來(lái)實(shí)現(xiàn)。
  3. 配置異常處理和會(huì)話(huà)管理:確保我們的應(yīng)用是無(wú)狀態(tài)的,并且正確處理認(rèn)證和授權(quán)異常。

5. 結(jié)果

經(jīng)過(guò)這些配置,前端可以順利地與后端通信,避免了 CORS 錯(cuò)誤。整個(gè)過(guò)程讓我對(duì) CORS 配置有了更深入的理解。

以上就是SpringBoot+Vue跨域配置(CORS)問(wèn)題得解決過(guò)程的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot Vue跨域配置解決的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • SpringBoot應(yīng)用啟動(dòng)失敗:端口占用導(dǎo)致Tomcat啟動(dòng)失敗的問(wèn)題分析與解決方法

    SpringBoot應(yīng)用啟動(dòng)失?。憾丝谡加脤?dǎo)致Tomcat啟動(dòng)失敗的問(wèn)題分析與解決方法

    在開(kāi)發(fā)和運(yùn)維過(guò)程中,應(yīng)用程序啟動(dòng)失敗是我們經(jīng)常遇到的一個(gè)問(wèn)題,尤其是在 Web 應(yīng)用程序中,涉及到 Web 服務(wù)器的配置時(shí),今天我們將探討一個(gè)常見(jiàn)的啟動(dòng)錯(cuò)誤,尤其是在使用 Spring Boot 和內(nèi)嵌 Tomcat 服務(wù)器時(shí),需要的朋友可以參考下
    2024-11-11
  • java更改圖片大小示例分享

    java更改圖片大小示例分享

    這篇文章主要介紹了java更改圖片大小示例,方法中指定路徑 ,舊文件名稱(chēng) ,新文件名稱(chēng),n 改變倍數(shù)就可以完成更改圖片大小,需要的朋友可以參考下
    2014-03-03
  • springboot整合kaptcha驗(yàn)證碼的示例代碼

    springboot整合kaptcha驗(yàn)證碼的示例代碼

    kaptcha是一個(gè)很有用的驗(yàn)證碼生成工具,本篇文章主要介紹了springboot整合kaptcha驗(yàn)證碼的示例代碼,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2018-06-06
  • 淺析Alibaba Nacos注冊(cè)中心源碼剖析

    淺析Alibaba Nacos注冊(cè)中心源碼剖析

    這篇文章主要介紹了淺析Alibaba Nacos注冊(cè)中心源碼剖析,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-05-05
  • Java后臺(tái)批量生產(chǎn)echarts圖表并保存圖片

    Java后臺(tái)批量生產(chǎn)echarts圖表并保存圖片

    這篇文章主要介紹了Java后臺(tái)批量生產(chǎn)echarts圖表并保存圖片,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-05-05
  • java IO流 之 輸出流 OutputString()的使用

    java IO流 之 輸出流 OutputString()的使用

    這篇文章主要介紹了java IO流 之 輸出流 OutputString()的使用的相關(guān)資料,需要的朋友可以參考下
    2016-12-12
  • Spring?Boot在啟動(dòng)時(shí)執(zhí)行一次的功能實(shí)現(xiàn)

    Spring?Boot在啟動(dòng)時(shí)執(zhí)行一次的功能實(shí)現(xiàn)

    這篇文章主要給大家介紹了關(guān)于Spring?Boot在啟動(dòng)時(shí)執(zhí)行一次的功能實(shí)現(xiàn),在實(shí)習(xí)過(guò)程中,有時(shí)候會(huì)遇到一些項(xiàng)目啟動(dòng)初始化的需求,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2023-08-08
  • Java 通過(guò)反射給實(shí)體類(lèi)賦值操作

    Java 通過(guò)反射給實(shí)體類(lèi)賦值操作

    這篇文章主要介紹了Java 通過(guò)反射給實(shí)體類(lèi)賦值操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-08-08
  • Spring 框架之Springfox使用詳解

    Spring 框架之Springfox使用詳解

    Springfox是Spring框架的API文檔工具,集成Swagger規(guī)范,自動(dòng)生成文檔并支持多語(yǔ)言/版本,模塊化設(shè)計(jì)便于擴(kuò)展,但存在版本兼容性、性能開(kāi)銷(xiāo)及對(duì)WebFlux支持不足等缺點(diǎn),適合傳統(tǒng)SpringMVC項(xiàng)目,本文介紹Springfox使用,感興趣的朋友一起看看吧
    2025-06-06
  • Java 類(lèi)與對(duì)象超基礎(chǔ)講解

    Java 類(lèi)與對(duì)象超基礎(chǔ)講解

    類(lèi)(class)和對(duì)象(object)是兩種以計(jì)算機(jī)為載體的計(jì)算機(jī)語(yǔ)言的合稱(chēng)。對(duì)象是對(duì)客觀事物的抽象,類(lèi)是對(duì)對(duì)象的抽象。類(lèi)是一種抽象的數(shù)據(jù)類(lèi)型
    2022-03-03

最新評(píng)論

吉安市| 闵行区| 禹城市| 东安县| 利辛县| 雅江县| 鄯善县| 仲巴县| 吴江市| 葵青区| 论坛| 正宁县| 甘泉县| 沙湾县| 西安市| 哈巴河县| 河间市| 克山县| 辽源市| 兴安县| 阿合奇县| 永仁县| 汨罗市| 左云县| 定日县| 德清县| 临西县| 五常市| 日土县| 井冈山市| 安溪县| 定结县| 马尔康县| 称多县| 沁水县| 凌源市| 阳朔县| 高青县| 英山县| 新宁县| 武城县|