91aaa在线国内观看,亚洲AV午夜福利精品一区二区,久久偷拍人视频,久久播这里有免费视播

<strong id="fvuar"></strong>

  • <sub id="fvuar"><dl id="fvuar"><em id="fvuar"></em></dl></sub>

    1. 千鋒教育-做有情懷、有良心、有品質(zhì)的職業(yè)教育機構(gòu)

      手機站
      千鋒教育

      千鋒學習站 | 隨時隨地免費學

      千鋒教育

      掃一掃進入千鋒手機站

      領取全套視頻
      千鋒教育

      關注千鋒學習站小程序
      隨時隨地免費學習課程

      當前位置:首頁  >  技術干貨  > 爆破專欄丨Spring Security系列教程解決Spring Security環(huán)境中的跨域問題

      爆破專欄丨Spring Security系列教程解決Spring Security環(huán)境中的跨域問題

      來源:千鋒教育
      發(fā)布人:qyf
      時間: 2021-10-29 11:40:00 1635478800

        原創(chuàng):千鋒一一哥

        前言

        上一章節(jié)中,一一哥 給各位講解了同源策略和跨域問題,以及跨域問題的解決方案,在本篇文章中,我會帶大家進行代碼實現(xiàn),看看在Spring Security環(huán)境中如何解決跨域問題。

        一. 啟用Spring Security 的CORS支持

        1. 創(chuàng)建web接口

        我先在SpringBoot環(huán)境中,創(chuàng)建一個端口號為8080的web項目,注意這個web項目沒有引入Spring Security的依賴包。然后在其中創(chuàng)建一個IndexController,定義兩個測試接口以便被ajax進行跨域訪問。8080項目的代碼結(jié)構(gòu):

        @RestController

        public class IndexController {

        @GetMapping("/hello")

        public String hello() {

        return "get hello";

        }

        @PostMapping("/hello")

        public String hello2() {

        return "post hello";

        }

        }

        請參考如下代碼結(jié)構(gòu)進行項目創(chuàng)建。

      圖片1

        2. 執(zhí)行ajax請求

        我們接下來再創(chuàng)建另一個端口號為8082的web項目,注意這個web項目也沒有引入Spring Security的依賴包。接著在這里定義一個index.html頁面,利用ajax跨域訪問8080項目中的web接口。

        8082項目的代碼結(jié)構(gòu):

      <!DOCTYPE html>

      <html lang="en">

      <head>

          <meta charset="UTF-8">

          <title>Index</title>

          <script type="text/javascript" src="jquery-2.1.0.js"></script>

      </head>

      <body>

      <div id="app"></div>

      <input type="button" onclick="btnClick()" value="get請求">

      <input type="button" onclick="btnClick2()" value="post請求">

       

      <script>

          function btnClick() {

              $.get('http://localhost:8080/hello', function (msg) {

                  $("#app").html(msg);

              });

          }

       

          function btnClick2() {

              $.post('http://localhost:8080/hello', function (msg) {

                  $("#app").html(msg);

              });

          }

      </script>

       

      </body>

      </html>  

        請參考如下代碼結(jié)構(gòu)進行項目創(chuàng)建。

      圖片2

        3. 發(fā)起跨域請求

        我們訪問8082項目中的index.html頁面,然后分別執(zhí)行get與post請求,這時候就可以在瀏覽器的控制臺上看到產(chǎn)生了CORS跨域問題,出現(xiàn)了CORS error狀態(tài),在請求頭中出現(xiàn)了Referer Policy: strict-origin-when-cross-origin。

      圖片3

      圖片4

        4. 解決跨域問題

        既然現(xiàn)在產(chǎn)生了跨域問題,那么該怎么解決呢?其實我們可以采用如下兩種方式之一來解決跨域問題。

        方式1:在接口方法上利用@CrossOrigin注解解決跨域問題

        @RestController

        public class IndexController {

        @CrossOrigin(value = "http://localhost:8082")

        @GetMapping("/hello")

        public String hello() {

        return "get hello";

        }

        @CrossOrigin(value = "http://localhost:8082")

        @PostMapping("/hello")

        public String hello2() {

        return "post hello";

        }

        }

        方式2:通過實現(xiàn)WebMvcConfigurer接口來解決跨域問題

        @Configuration

        public class WebMvcConfig implements WebMvcConfigurer {

        @Override

        public void addCorsMappings(CorsRegistry registry) {

        registry.addMapping("/**")

        .allowedOrigins("http://localhost:8082")

        .allowedMethods("*")

        .allowedHeaders("*");

        }

        }

        當進行了跨域設置之后,我們再次進行跨域請求,就可以看到請求成功了。

      圖片5

        二. Spring Security環(huán)境下的跨域問題解決

        1. 引入Spring Security依賴

        通過上面的配置,我們已經(jīng)解決了Ajax的跨域請求問題,但是這個案例中也有潛在的威脅存在,常見的就是 CSRF(Cross-site request forgery) 跨站請求偽造。跨站請求偽造也被稱為 one-click attack 或者 session riding,通常縮寫為 CSRF 或者 XSRF,是一種挾制用戶在當前已登錄的 Web 應用程序上執(zhí)行非本意的操作的攻擊方法。

        所以為了提高網(wǎng)站的安全性,我在上面Spring Boot項目的基礎之上,添加Spring Security的依賴包,但是暫時不進行任何別的操作。

        <dependencies>

              <dependency>

                  <groupId>org.springframework.boot</groupId>

                  <artifactId>spring-boot-starter-web</artifactId>

              </dependency>

       

              <dependency>

                  <groupId>org.springframework.boot</groupId>

                  <artifactId>spring-boot-starter-security</artifactId>

              </dependency>

          </dependencies>

        2. 重啟8080項目進行測試

        接著我就重啟8080這個Spring Boot項目,然后在8082項目中再次進行跨域請求,我們會發(fā)現(xiàn)在引入Spring Security后,再次產(chǎn)生了跨域問題。

      圖片6

        3. 解決Spring Security環(huán)境下跨域問題的3種方案

        通過實驗可知,如果使用了 Spring Security,上面的跨域配置會失效,因為請求會被 Spring Security 攔截。那么在Spring Security環(huán)境中,如何解決跨域問題呢?這里我們有3種方式可以開啟 Spring Security 對跨域的支持。

        3.1 方式一:開啟cors方法

        我們在上面的案例之上,編寫一個SecurityConfig配置類,在configure方法中,利用cors() 開啟Spring Security 對 CORS 的支持:

        @EnableWebSecurity

        public class SecurityConfig extends WebSecurityConfigurerAdapter {

        @Override

        protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()

        .anyRequest()

        .permitAll()

        .and()

        .formLogin()

        .permitAll()

        .and()

        .httpBasic()

        .and()

        //支持跨域訪問

        .cors()

        .and()

        .csrf()

        .disable();

        }

        }

        3.2 方式二:進行全局配置

        第二種方式是去除上面的跨域配置,直接在 Spring Security 中做全局配置,如下:

        @EnableWebSecurity

        public class SecurityConfig extends WebSecurityConfigurerAdapter {

        @Override

        protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()

        .anyRequest()

        .permitAll()

        .and()

        .formLogin()

        .permitAll()

        .and()

        .httpBasic()

        .and()

        //支持跨域訪問

        .cors()

        .configurationSource(corsConfigurationSource())

        .and()

        .csrf()

        .disable();

        }

        @Bean

        public CorsConfigurationSource corsConfigurationSource() {

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

        CorsConfiguration configuration = new CorsConfiguration();

        configuration.setAllowCredentials(true);

        configuration.setAllowedOrigins(Collections.singletonList("*"));

        configuration.setAllowedMethods(Collections.singletonList("*"));

        configuration.setAllowedHeaders(Collections.singletonList("*"));

        configuration.setMaxAge(Duration.ofHours(1));

        source.registerCorsConfiguration("/**", configuration);

        return source;

        }

        }

        以上2個方法,都可以實現(xiàn)在Spring Security環(huán)境下的跨域訪問。

        3.3 方式三:支持OAuth2的跨域訪問

        我們開發(fā)時,還有一種情況就是支持 OAuth2 相關接口的跨域,比如用戶要訪問 OAuth2 中的 /oauth/token 等接口。我們可以配置一個全局的 CorsFilter 跨域過濾器類,核心代碼如下:

        /**

        * 跨域配置方式3:定義全局跨域過濾器

        **/

        @Configuration

        public class GlobalCorsConfiguration {

        @Bean

        public CorsFilter corsFilter() {

        CorsConfiguration corsConfiguration = new CorsConfiguration();

        corsConfiguration.setAllowCredentials(true);

        corsConfiguration.addAllowedOrigin("*");

        corsConfiguration.addAllowedHeader("*");

        corsConfiguration.addAllowedMethod("*");

        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();

        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);

        return new CorsFilter(urlBasedCorsConfigurationSource);

        }

        }

        @EnableWebSecurity

        public class SecurityConfig extends WebSecurityConfigurerAdapter {

        @Override

        protected void configure(HttpSecurity http) throws Exception {

        //跨域方式3:

        http.requestMatchers()

        .antMatchers(HttpMethod.OPTIONS, "/oauth/**")

        .and()

        .csrf()

        .disable()

        .formLogin()

        .and()

        .cors();

        }

        }

        該方式也可以實現(xiàn)Spring Security中的跨域訪問。

        4. 代碼結(jié)構(gòu)

        以下是本案例的代碼結(jié)構(gòu),可以參考下圖進行項目創(chuàng)建:

      圖片7

        至此,我就帶各位解決了Spring Security環(huán)境中的跨域問題,你學會了嗎?

      圖片8

      關注WX公眾號【Java架構(gòu)棧】,跟著千鋒一起學Java

      tags:
      聲明:本站稿件版權(quán)均屬千鋒教育所有,未經(jīng)許可不得擅自轉(zhuǎn)載。
      10年以上業(yè)內(nèi)強師集結(jié),手把手帶你蛻變精英
      請您保持通訊暢通,專屬學習老師24小時內(nèi)將與您1V1溝通
      免費領取
      今日已有369人領取成功
      劉同學 138****2860 剛剛成功領取
      王同學 131****2015 剛剛成功領取
      張同學 133****4652 剛剛成功領取
      李同學 135****8607 剛剛成功領取
      楊同學 132****5667 剛剛成功領取
      岳同學 134****6652 剛剛成功領取
      梁同學 157****2950 剛剛成功領取
      劉同學 189****1015 剛剛成功領取
      張同學 155****4678 剛剛成功領取
      鄒同學 139****2907 剛剛成功領取
      董同學 138****2867 剛剛成功領取
      周同學 136****3602 剛剛成功領取
      相關推薦HOT
      有什么工具能進行服務器性能監(jiān)控?

      一、NagiosNagios是一款廣泛使用的開源監(jiān)控工具,用于監(jiān)控服務器、網(wǎng)絡設備和應用程序的狀態(tài)和性能。它支持對各種指標的監(jiān)控,如CPU使用率、內(nèi)...詳情>>

      2023-10-14 00:12:36
      應用服務器與Web服務器有什么區(qū)別?

      一、功能定位不同應用服務器是一種軟件平臺,用于提供各種應用程序的運行環(huán)境。它負責管理和執(zhí)行應用程序的邏輯,處理數(shù)據(jù)傳輸和事務管理等任務...詳情>>

      2023-10-14 00:05:39
      番茄工作法的優(yōu)點和缺陷都有哪些?

      一、番茄工作法概述番茄工作法是一種時間管理技術,旨在提高工作效率和集中注意力。該方法由弗朗西斯科·西里洛于1980年代開發(fā),并逐漸流行起來...詳情>>

      2023-10-14 00:00:49
      PHP數(shù)組具的特性有哪些?

      一、有序集合PHP數(shù)組是一個有序的數(shù)據(jù)集合,它可以存儲多個值,并使用索引來訪問這些值。索引可以是數(shù)字或字符串,允許你以靈活的方式組織和訪...詳情>>

      2023-10-13 23:46:55
      C語言中定義與聲明的含義是什么?

      一、定義的含義在C語言中,定義是指為變量、函數(shù)或類型分配存儲空間并指定其屬性和初始值的過程。定義的主要含義如下:分配存儲空間:定義一個...詳情>>

      2023-10-13 23:32:41