SpringBoot+SpringSecurity無法實現(xiàn)跨域如何解決

本篇內(nèi)容主要講解“SpringBoot+Spring Security無法實現(xiàn)跨域如何解決”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“SpringBoot+Spring Security無法實現(xiàn)跨域如何解決”吧!

在花都等地區(qū),都構(gòu)建了全面的區(qū)域性戰(zhàn)略布局,加強發(fā)展的系統(tǒng)性、市場前瞻性、產(chǎn)品創(chuàng)新能力,以專注、極致的服務(wù)理念,為客戶提供成都網(wǎng)站設(shè)計、做網(wǎng)站 網(wǎng)站設(shè)計制作按需網(wǎng)站制作,公司網(wǎng)站建設(shè),企業(yè)網(wǎng)站建設(shè),品牌網(wǎng)站建設(shè),全網(wǎng)整合營銷推廣,外貿(mào)網(wǎng)站建設(shè),花都網(wǎng)站建設(shè)費用合理。

SpringBoot+Spring Security無法實現(xiàn)跨域

未使用Security時跨域:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.*;
@Configuration
@AutoConfigureBefore(SecurityConfig.class)
public class MyMvcConfigurer implements WebMvcConfigurer {
    public void addCorsMappings(CorsRegistry registry){
        LOGGER.info("跨域已設(shè)置");
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("*")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }
}

整合Security時發(fā)現(xiàn)只用上述方法前后端分離時仍存在跨域問題,

解決方法如下:

@Configuration
@AutoConfigureBefore(Swagger2Configuration.class)
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(-1)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .loginProcessingUrl("/user/login")
                .loginPage("/singIn.html")
                .successHandler(moyuAuthenticationSuccessHandler)
                .failureHandler(moyuAuthenticationFailureHandler)
                .and()
                .apply(moyuSocialSecurityConfig)
                .and()
                .rememberMe()
                .tokenRepository(persistentTokenRepository())
                .tokenValiditySeconds(3600*24*7)
                .userDetailsService(userDetailsService)
                .and()
                .authorizeRequests()
                .antMatchers("/user/login","/login","/singIn.html","**","/**").permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .cors()
                .and()
                .csrf().disable();
    }
}

重點加入代碼:

   .and()
   .cors()//新加入
   .and()
   .csrf().disable();

引用Spring Security 項目的跨域處理

最近項目采用了前后端分離的框架,前端和后臺接口沒有部署到一個站點,出現(xiàn)了跨域問題,什么是跨域,這里就不再贅述,直接說解決辦法。

Spring 解決跨域的方式有很多,個人采用了Crosfilter的方式

具體代碼如下:

@Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new      UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }

配置完成后,測試調(diào)用,報錯401,依然不行。網(wǎng)上查資料得知,跨域請求會進行兩次。具體流程見下圖:

SpringBoot+Spring Security無法實現(xiàn)跨域如何解決

每次跨域請求,真正請求到達后端之前,瀏覽器都會先發(fā)起一個preflight request,請求方式為OPTIONS 詢問服務(wù)端是否接受該跨域請求,具體參數(shù)如下圖:

SpringBoot+Spring Security無法實現(xiàn)跨域如何解決

但是該請求不能攜帶cookie和自己定義的header。

由于項目中引入了Spring security ,而我使用的token傳遞方式是在header中使用authorization 字段,這樣依賴Spring Security攔截到 preflight request 發(fā)現(xiàn)它沒有攜帶token,就會報錯401,沒有授權(quán)。

解決這個問題很簡單,可以使用以下配置

讓Spring security 不校驗preflight request 。

 @Override
    public void configure(HttpSecurity http) throws Exception {
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry 
        = http.authorizeRequests();
        registry.requestMatchers(CorsUtils::isPreFlightRequest).permitAll();//讓Spring security放行所有preflight request 
    }

再試就搞定了,但是后端直接配置支持跨域會導(dǎo)致兩次請求。還使用另一種方式,使用Nginx 轉(zhuǎn)發(fā)一下請求也可以。

到此,相信大家對“SpringBoot+Spring Security無法實現(xiàn)跨域如何解決”有了更深的了解,不妨來實際操作一番吧!這里是創(chuàng)新互聯(lián)網(wǎng)站,更多相關(guān)內(nèi)容可以進入相關(guān)頻道進行查詢,關(guān)注我們,繼續(xù)學習!

新聞名稱:SpringBoot+SpringSecurity無法實現(xiàn)跨域如何解決
當前URL:http://muchs.cn/article10/gpjego.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供面包屑導(dǎo)航、做網(wǎng)站App設(shè)計、域名注冊Google、用戶體驗

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站建設(shè)網(wǎng)站維護公司