<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          SpringBoot 實現(xiàn)圖片防盜鏈功能

          共 12678字,需瀏覽 26分鐘

           ·

          2024-04-28 00:00

          程序員的成長之路
          互聯(lián)網(wǎng)/程序員/技術(shù)/資料共享 
          關(guān)注


          閱讀本文大概需要 4 分鐘。

          來自:blog.csdn.net/weixin_46157208/article/details/138051737

          前言

          出于安全考慮,我們需要后端返回的圖片只允許在某個網(wǎng)站內(nèi)展示,不想被爬蟲拿到圖片地址后被下載。或者,不想瀏覽器直接訪問圖片鏈接。
          出于性能考慮,不想要別人的網(wǎng)站,拿著我們的圖片鏈接去展示,白白消耗自己的服務(wù)器資源。
          故而可在springboot中,使用簡單的圖片防盜鏈規(guī)則。攔截掉一些處理。

          1、代碼實現(xiàn)

          本篇實戰(zhàn)代碼是簡易版,代碼寫死配置
          1-1、創(chuàng)建攔截器類

          import org.springframework.web.servlet.HandlerInterceptor;
          import org.springframework.web.servlet.ModelAndView;
          import javax.servlet.http.HttpServletRequest;
          import javax.servlet.http.HttpServletResponse;

          public class ImageProtectionInterceptor implements HandlerInterceptor {

              private static final String ALLOWED_DOMAIN = "baidudu.com"// 允許的域名

              @Override
              public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                  // 獲取請求的 URL
                  String requestUrl = request.getRequestURL().toString();

                  // 判斷請求是否以圖片后綴結(jié)尾
                  if (requestUrl.endsWith(".jpg") || requestUrl.endsWith(".png") || requestUrl.endsWith(".jpeg")) {
                      // 獲取請求的來源域名
                      String referer = request.getHeader("Referer");

                      // 檢查來源域名是否符合預(yù)期
                      if (referer != null && referer.contains(ALLOWED_DOMAIN)) {
                          return true// 符合防盜鏈要求,放行請求
                      } else {
                          response.sendError(HttpServletResponse.SC_FORBIDDEN); // 返回 403 Forbidden
                          return false// 攔截請求
                      }
                  }

                  return true// 對非圖片資源請求放行
              }
          }

          1-2、注冊攔截器

          import org.springframework.context.annotation.Configuration;
          import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
          import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

          @Configuration
          public class WebConfig implements WebMvcConfigurer {

              @Override
              public void addInterceptors(InterceptorRegistry registry) {
                  // 注冊攔截器,攔截所有請求
                  registry.addInterceptor(new ImageProtectionInterceptor())
                          .addPathPatterns("/**"); // 攔截所有請求
              }
          }

          2、代碼實現(xiàn)(靈活配置)

          2-1、在 application.yml 中配置信息

          # 圖片防盜鏈配置
          img-protect:
            # 圖片防盜鏈保護開關(guān)
            enabled: true
            # 是否允許瀏覽器直接訪問
            allowBrowser: false
            # 圖片防盜鏈白名單,多個用逗號分隔【不填則所有網(wǎng)站都攔截】
            allowReferer: baidudu.com

          2-2、創(chuàng)建配置文件映射類


          import org.springframework.boot.context.properties.ConfigurationProperties;
          import org.springframework.stereotype.Component;

          @Component
          @ConfigurationProperties("img-protect")
          public class ImgProtectConfig {

              private boolean enabled;
              private boolean allowBrowser;

              private String allowReferer;

              public boolean getEnabled() {
                  return enabled;
              }

              public void setEnabled(boolean enabled) {
                  this.enabled = enabled;
              }

              public boolean getAllowBrowser() {
                  return allowBrowser;
              }

              public void setAllowBrowser(boolean allowBrowser) {
                  this.allowBrowser = allowBrowser;
              }

              public String getAllowReferer() {
                  return allowReferer;
              }

              public void setAllowReferer(String allowReferer) {
                  this.allowReferer = allowReferer;
              }
          }

          2-3、創(chuàng)建攔截器類


          import 上方2-2創(chuàng)建的類路徑.ImgProtectConfig;
          import org.springframework.beans.factory.annotation.Autowired;
          import org.springframework.stereotype.Component;
          import org.springframework.web.servlet.HandlerInterceptor;
          import javax.servlet.http.HttpServletRequest;
          import javax.servlet.http.HttpServletResponse;
          import java.util.Arrays;
          import java.util.HashSet;
          import java.util.Set;

          @Component
          public class ImageProtectionInterceptor implements HandlerInterceptor {

              @Autowired
              private ImgProtectConfig imgProtectConfig;

              @Override
              public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

            // 判斷是否開啟圖片防盜鏈功能
                  if (!imgProtectConfig.getEnabled()){
                      return true;
                  }
                  
                  // 獲取請求的 URL
                  String requestUrl = request.getRequestURL().toString();

                  // 判斷請求是否以圖片后綴結(jié)尾
                  if (requestUrl.endsWith(".jpg") || requestUrl.endsWith(".png") || requestUrl.endsWith(".jpeg")) {
                      // 獲取請求的來源域名
                      String referer = request.getHeader("Referer");

                      // 檢查來源域名是否符合預(yù)期,referer 為 null 則說明是瀏覽器直接訪問。
                      if (referer == null && imgProtectConfig.getAllowBrowser()){
                          return true// 符合防盜鏈要求,放行請求
                      }else if (referer != null && isAllowedDomain(referer)) {
                          return true// 符合防盜鏈要求,放行請求
                      } else {
                          response.sendError(HttpServletResponse.SC_FORBIDDEN); // 返回 403 Forbidden
                          return false// 攔截請求
                      }
                  }

                  return true// 對非圖片資源請求放行
              }


              // 檢查是否來自允許的域名
              private boolean isAllowedDomain(String referer) {
                  // 獲取允許的域名
                  String allowedReferers = imgProtectConfig.getAllowReferer();
                  // 如果允許的域名不為空
                  if (allowedReferers.trim() != null && !"".equals(allowedReferers.trim())) {
                      // 將允許的域名分割成字符串?dāng)?shù)組
                      Set<String> allowedDomains = new HashSet<>(Arrays.asList(allowedReferers.split(",")));
                      // 遍歷允許的域名
                      for (String allowedDomain : allowedDomains) {
                          // 如果請求的域名包含允許的域名,則返回true
                          if (referer.contains(allowedDomain.trim())) {
                              return true;
                          }
                      }
                  }
                  // 否則返回false
                  return false;
              }

          }

          2-4、注冊攔截器

          import org.springframework.context.annotation.Configuration;
          import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
          import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

          @Configuration
          public class WebConfig implements WebMvcConfigurer {
           

           // 不能再使用 new 方式創(chuàng)建對象 !!! 
           @Autowired
              private ImageProtectionInterceptor imageProtectionInterceptor;


              @Override
              public void addInterceptors(InterceptorRegistry registry) {
                  // 注冊攔截器,攔截所有請求
                  registry.addInterceptor(imageProtectionInterceptor)
                          .addPathPatterns("/**"); // 攔截所有請求
              }
          }

          結(jié)束語

          以上防盜鏈攔截器基本實現(xiàn)可以對付一般情況下的圖片盜鏈,但并不能保證絕對安全。
          可能出現(xiàn)以下等情況:
          • Referer 偽造: 惡意客戶端可以偽造 referer 頭。攻擊者可以偽造有效的 referer 來繞過保護。
          • 漏報: 攻擊者可能找到繞過 referer 檢查的方法(例如使用 data URI 或 base64 編碼的圖片)。
          • 誤報: 合法用戶可能因為 referer 不匹配而被阻止(例如隱私瀏覽器或代理服務(wù)器)。
          • 反向代理: 攻擊者可以在url路徑中,添加域名白名單作為反向代理路徑,繞開代碼的contains方法檢查。
          <END>

          推薦閱讀:

          GitHub上特殊版「某音」,火了!

          加密后的敏感字段還能進行模糊查詢嗎?

             
          互聯(lián)網(wǎng)初中高級大廠面試題(9個G)

          內(nèi)容包含Java基礎(chǔ)、JavaWeb、MySQL性能優(yōu)化、JVM、鎖、百萬并發(fā)、消息隊列、高性能緩存、反射、Spring全家桶原理、微服務(wù)、Zookeeper......等技術(shù)棧!

          ?戳閱讀原文領(lǐng)取!                                  朕已閱 

          瀏覽 62
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  日本三级高清视频组 | 国模精品| 靠逼视频免费的 | 麻豆网站 | 五月天免费黄色视频 |