最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

vue前端img訪問鑒權(quán)后端進行攔截的代碼示例

 更新時間:2024年03月15日 09:23:18   作者:wengelovelian  
路由攔截是一種在用戶訪問特定頁面之前對其進行攔截和處理的機制,下面這篇文章主要給大家介紹了關于vue前端img訪問鑒權(quán)后端進行攔截的相關資料,需要的朋友可以參考下

前言

此文章為了解決匿名可以訪問圖片問題,有的文章是重構(gòu)了el-img組件,使用blob重新進行加載。該文章是換個思路,在圖片訪問地址后面追加token參數(shù),后端進行攔截,判斷token是否有效,無效則攔截。反之通過。同時會校驗是否同一臺電腦、同一瀏覽器、同一操作系統(tǒng)、同一登錄地點

前端:

image-preview組件:

<template>
  <el-image
    :src="`${realSrc}`"
    fit="cover"
    :style="`width:${realWidth};height:${realHeight};`"
    :preview-src-list="realSrcList"
    append-to-body="true"
  >
    <template #error>
      <div class="image-slot">
        <el-icon><picture-filled /></el-icon>
      </div>
    </template>
  </el-image>
</template>

<script setup>
import { isExternal } from "@/utils/validate";
import { getToken } from "@/utils/auth";
import {watch} from "vue";

const tokenInfo = ref(getToken())

const props = defineProps({
  src: {
    type: String,
    required: true
  },
  srcViewerList: {
    type: Array
  },
  width: {
    type: [Number, String],
    default: ""
  },
  height: {
    type: [Number, String],
    default: ""
  }
});

const realSrc = computed(() => {
  let real_src = props.src.split(",")[0];
  if (isExternal(real_src)) {
    return real_src;
  }
  return import.meta.env.VITE_APP_BASE_API + real_src + '?token=' + tokenInfo.value;
});

const realSrcList = ref([]);
watch(() => {
  props.srcViewerList.forEach(item => {
    realSrcList.value.push(item + '?token=' + tokenInfo.value)
  });
})

// const realSrcList = computed(() => {
//   let real_src_list = props.src.split(",");
//   let srcList = [];
//   real_src_list.forEach(item => {
//     if (isExternal(item)) {
//       return srcList.push(item);
//     }
//     return srcList.push(import.meta.env.VITE_APP_BASE_API + item + '?token=' + tokenInfo.value);
//   });
//   return srcList;
// });

const realWidth = computed(() =>
  typeof props.width == "string" ? props.width : `${props.width}px`
);

const realHeight = computed(() =>
  typeof props.height == "string" ? props.height : `${props.height}px`
);
</script>

<style lang="scss" scoped>
.el-image {
  border-radius: 5px;
  background-color: #ebeef5;
  box-shadow: 0 0 5px 1px #ccc;
  :deep(.el-image__inner) {
    transition: all 0.3s;
    cursor: pointer;
    &:hover {
      transform: scale(1.2);
    }
  }
  :deep(.image-slot) {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    color: #909399;
    font-size: 30px;
  }
}
</style>

后端攔截器:

ProfileInterceptorConfig.java

package com.fuel.framework.config;

import com.fuel.framework.interceptor.ProfileInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 通用配置
 * 
 * @author hhxx
 */
@Configuration
public class ProfileInterceptorConfig implements WebMvcConfigurer
{
    @Autowired
    private ProfileInterceptor profileInterceptor;

    /**
     * 自定義攔截規(guī)則
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry)
    {
        registry.addInterceptor(profileInterceptor)
                .addPathPatterns("/profile/**");
    }

}

ProfileInterceptor.java

package com.fuel.framework.interceptor;

import com.alibaba.fastjson2.JSON;
import com.fuel.common.constant.HttpStatus;
import com.fuel.common.core.domain.AjaxResult;
import com.fuel.common.core.domain.model.LoginUser;
import com.fuel.common.utils.ServletUtils;
import com.fuel.common.utils.StringUtils;
import com.fuel.common.utils.ip.AddressUtils;
import com.fuel.common.utils.ip.IpUtils;
import com.fuel.common.utils.spring.SpringUtils;
import com.fuel.framework.security.handle.AuthenticationEntryPointImpl;
import com.fuel.framework.web.service.TokenService;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class ProfileInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        //獲取token
        String token = request.getParameter("token");
        // 獲取用戶代理
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        // 獲取ip
        String ipaddr = IpUtils.getIpAddr(ServletUtils.getRequest());
        // 獲取登錄地點
        String loginLocation = AddressUtils.getRealAddressByIP(ipaddr);
        // 獲取瀏覽器
        String browser = userAgent.getBrowser().getName();
        // 獲取操作系統(tǒng)
        String os = userAgent.getOperatingSystem().getName();
        TokenService bean = SpringUtils.getBean(TokenService.class);
        AuthenticationEntryPointImpl authenticationEntryPointImpl = SpringUtils.getBean(AuthenticationEntryPointImpl.class);
        // 校驗token是否有效
        Map<String, Object> stringObjectMap = bean.verifyToken(token);
        boolean bl = false;
        if (stringObjectMap.size() > 0) {
            // 獲取登錄信息
            LoginUser user = (LoginUser) stringObjectMap.get("user");
            // 判斷是否同一臺電腦、同一瀏覽器、同一操作系統(tǒng)、同一登錄地點
            if (user != null && ipaddr.equals(user.getIpaddr()) && loginLocation.equals(user.getLoginLocation()) && browser.equals(user.getBrowser()) && os.equals(user.getOs())) {
                bl = true;
            }
        }
        if(!bl){
            // 校驗不通過時返回錯誤信息--復用Spring Security框架的信息
            authenticationEntryPointImpl.commence(request, response, null);
        }
        return bl;
    }
}

TokenService.java

package com.fuel.framework.web.service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fuel.common.constant.Constants;
import com.fuel.common.core.domain.AjaxResult;
import com.fuel.common.core.domain.model.LoginUser;
import com.fuel.common.core.redis.RedisCache;
import com.fuel.common.utils.MessageUtils;
import com.fuel.common.utils.ServletUtils;
import com.fuel.common.utils.StringUtils;
import com.fuel.common.utils.http.HttpUtils;
import com.fuel.common.utils.ip.AddressUtils;
import com.fuel.common.utils.ip.IpUtils;
import com.fuel.common.utils.uuid.IdUtils;

import eu.bitwalker.useragentutils.UserAgent;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

/**
 * token驗證處理
 *
 * @author hhxx
 */
@Component
public class TokenService
{
    // 令牌自定義標識
    @Value("${token.header}")
    private String header;

    // 令牌秘鑰
    @Value("${token.secret}")
    private String secret;

    // 令牌有效期(默認30分鐘)
    @Value("${token.expireTime}")
    private int expireTime;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

    @Autowired
    private RedisCache redisCache;
    
    /***
     * 驗證令牌
     * @param token
     * @return
     */
    public Map<String,Object> verifyToken(String token) {
    	
    	Map<String,Object> resultMap = new HashMap<>();
    	boolean bl = true;
    	try {
    		Claims claims = parseToken(token);
    		// 解析對應的權(quán)限以及用戶信息
            String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
            String userKey = getTokenKey(uuid);
            LoginUser user = JSONObject.parseObject(redisCache.getCacheObject(userKey),LoginUser.class);
            if(user != null) {
            	bl = true;
            	resultMap.put("bl", bl);
            }else {
            	bl = false;
            	resultMap.put("bl", bl);
            	resultMap.put("msg", "token已過期");
            }
    	}catch (ExpiredJwtException  eje) {
            bl = false;
            resultMap.put("bl", bl);
        	resultMap.put("msg", "token已過期");
    	}
    	catch(Exception ex) {
    		bl = false;
    		resultMap.put("bl", bl);
        	resultMap.put("msg", "token驗證異常");
    	}
    	
    	return resultMap;
    }
}

總結(jié) 

到此這篇關于vue前端img訪問鑒權(quán)后端進行攔截的文章就介紹到這了,更多相關vue前端img訪問鑒權(quán)后端攔截內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • 如何使用Vue mapState快捷獲取Vuex state多個值

    如何使用Vue mapState快捷獲取Vuex state多個值

    這篇文章主要為大家介紹了如何使用Vue mapState快捷獲取Vuex state多個值實現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-06-06
  • vue如何實現(xiàn)上傳圖片和顯示圖片

    vue如何實現(xiàn)上傳圖片和顯示圖片

    這篇文章主要介紹了vue如何實現(xiàn)上傳圖片和顯示圖片問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-10-10
  • Vue+Java 通過websocket實現(xiàn)服務器與客戶端雙向通信操作

    Vue+Java 通過websocket實現(xiàn)服務器與客戶端雙向通信操作

    這篇文章主要介紹了Vue+Java 通過websocket實現(xiàn)服務器與客戶端雙向通信操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-09-09
  • vue如何引入sass全局變量

    vue如何引入sass全局變量

    sass或者less都提供變量設置,在需求切換主題的項目中使用less或者sass變量,這篇文章主要介紹了vue引入sass全局變量,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-06-06
  • vue-cli3項目配置eslint代碼規(guī)范的完整步驟

    vue-cli3項目配置eslint代碼規(guī)范的完整步驟

    這篇文章主要給大家介紹了關于vue-cli3項目配置eslint代碼規(guī)范的完整步驟,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-09-09
  • vue使用el-upload實現(xiàn)文件上傳的實例代碼

    vue使用el-upload實現(xiàn)文件上傳的實例代碼

    這篇文章主要為大家詳細介紹了vue使用el-upload實現(xiàn)文件上傳,文中示例代碼介紹的非常詳細,對大家的學習或工作有一定的幫助,感興趣的小伙伴們可以參考一下
    2024-01-01
  • Vue自定義指令實現(xiàn)按鈕級的權(quán)限控制的示例代碼

    Vue自定義指令實現(xiàn)按鈕級的權(quán)限控制的示例代碼

    在Vue中可以通過自定義指令來實現(xiàn)按鈕權(quán)限控制,本文主要介紹了Vue自定義指令實現(xiàn)按鈕級的權(quán)限控制的示例代碼,具有一定的參考價值,感興趣的可以了解一下
    2024-05-05
  • element實現(xiàn)合并單元格通用方法

    element實現(xiàn)合并單元格通用方法

    這篇文章主要介紹了element實現(xiàn)合并單元格通用方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-11-11
  • vue使用showdown并實現(xiàn)代碼區(qū)域高亮的示例代碼

    vue使用showdown并實現(xiàn)代碼區(qū)域高亮的示例代碼

    這篇文章主要介紹了vue使用showdown并實現(xiàn)代碼區(qū)域高亮的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-10-10
  • vue實現(xiàn)監(jiān)聽數(shù)值的變化,并捕捉到

    vue實現(xiàn)監(jiān)聽數(shù)值的變化,并捕捉到

    這篇文章主要介紹了vue實現(xiàn)監(jiān)聽數(shù)值的變化,并捕捉到問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-10-10

最新評論

嘉荫县| 新乡县| 五大连池市| 介休市| 微山县| 建宁县| 垦利县| 西乌珠穆沁旗| 南宫市| 玛纳斯县| 明星| 从江县| 如皋市| 理塘县| 闻喜县| 万载县| 玉林市| 崇州市| 洛南县| 介休市| 陵川县| 缙云县| 大姚县| 长宁区| 长春市| 沧州市| 和静县| 柳州市| 石棉县| 揭阳市| 盐城市| 宝坻区| 深水埗区| 容城县| 甘洛县| 盐边县| 赤壁市| 平湖市| 渝北区| 霍林郭勒市| 廊坊市|