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