SpringSecurity如何配置跨域訪問(wèn)
說(shuō)明
java后端web服務(wù)有很多種方法可以實(shí)現(xiàn)跨域訪問(wèn),配置很簡(jiǎn)單,今天這里我們用SpringSecurity的方式配置跨域訪問(wèn)
配置方法如下:
package com.wisea.config; import org.springframework.context.annotation.Bean; 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.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin("*"); corsConfiguration.addAllowedHeader("*"); corsConfiguration.addAllowedMethod("*"); corsConfiguration.setAllowCredentials(true); source.registerCorsConfiguration("/**", corsConfiguration); return new CorsFilter(source); } }
其他
看網(wǎng)上的配置里會(huì)有代碼如下:
@Override protected void configure(HttpSecurity http) throws Exception { http.cors(); ... }
實(shí)際上并不起什么作用,總結(jié),當(dāng)工程中開(kāi)啟了@EnableWebSecurity的時(shí)候,我們只需要讓spring容器中存在一個(gè)CorsFilter的跨域過(guò)濾器即可。
some days 幾天發(fā)現(xiàn)問(wèn)題:
當(dāng)請(qǐng)求的中有redirect時(shí),上面這段代碼就必須了。
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java微信公眾平臺(tái)開(kāi)發(fā)(9) 關(guān)鍵字回復(fù)以及客服接口實(shí)現(xiàn)
這篇文章主要為大家詳細(xì)介紹了Java微信公眾平臺(tái)開(kāi)發(fā)第九步,關(guān)鍵字回復(fù)以及客服接口實(shí)現(xiàn),以及遇到該公眾號(hào)暫時(shí)無(wú)法提供服務(wù)的解決方案,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-04-04SpringBoot上傳圖片到指定位置并返回URL的實(shí)現(xiàn)
本文主要介紹了SpringBoot上傳圖片到指定位置并返回URL,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下<BR>2022-03-03Java使用Hutool執(zhí)行日期的加法和減法操作方法
使用Hutool進(jìn)行日期的加法和減法操作,可以使用`DateUtil.offsetXXX()`方法來(lái)實(shí)現(xiàn),這些方法會(huì)返回一個(gè)新的日期,而不是在原日期上進(jìn)行修改,本文給大家介紹Java使用Hutool執(zhí)行日期的加法和減法操作方法,感興趣的朋友一起看看吧2023-11-11談?wù)凧ava類型中ParameterizedType,GenericArrayType,TypeVariabl,Wild
這篇文章主要介紹Java類型中ParameterizedType,GenericArrayType,TypeVariabl,WildcardType的相關(guān)資料,需要的朋友可以參考下2015-10-10Java基于面向?qū)ο髮?shí)現(xiàn)一個(gè)戰(zhàn)士小游戲
這篇文章主要為大家詳細(xì)介紹了Java如何基于面向?qū)ο髮?shí)現(xiàn)一個(gè)戰(zhàn)士小游戲,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以動(dòng)手嘗試一下2022-07-07Thymeleaf渲染網(wǎng)頁(yè)時(shí)中文亂碼的問(wèn)題及解決
這篇文章主要介紹了Thymeleaf渲染網(wǎng)頁(yè)時(shí)中文亂碼的問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02Druid關(guān)閉監(jiān)控頁(yè)面關(guān)閉不了的問(wèn)題及解決
這篇文章主要介紹了Druid關(guān)閉監(jiān)控頁(yè)面關(guān)閉不了的問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05