SoFunction
Updated on 2025-04-12

Example of code for intercepting img access authentication backend with vue front-end

Preface

In order to solve the problem of anonymous access to images, some articles refactored the el-img component and reloaded it using blob. This article is a different idea. Add token parameters after the image access address, and intercept the backend to determine whether the token is valid. If it is invalid, it will be intercepted. Otherwise, pass. At the same time, it will check whether the same computer, same browser, same operating system, same login location

front end:

image-preview component:

<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 = (",")[0];
  if (isExternal(real_src)) {
    return real_src;
  }
  return .VITE_APP_BASE_API + real_src + '?token=' + ;
});

const realSrcList = ref([]);
watch(() => {
  (item => {
    (item + '?token=' + )
  });
})

// const realSrcList = computed(() => {
//   let real_src_list = (",");
//   let srcList = [];
//   real_src_list.forEach(item => {
//     if (isExternal(item)) {
//       return (item);
//     }
//     return (.VITE_APP_BASE_API + item + '?token=' + );
//   });
//   return srcList;
// });

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

const realHeight = computed(() =>
  typeof  == "string" ?  : `${}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>

Backend Interceptor:

package ;

import ;
import ;
import ;
import ;
import ;

/**
  * General configuration
  *
  * @author hhxx
  */
@Configuration
public class ProfileInterceptorConfig implements WebMvcConfigurer
{
    @Autowired
    private ProfileInterceptor profileInterceptor;

    /**
      * Custom interception rules
      */
    @Override
    public void addInterceptors(InterceptorRegistry registry)
    {
        (profileInterceptor)
                .addPathPatterns("/profile/**");
    }

}

package ;

import .;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

import ;
import ;
import ;

@Component
public class ProfileInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        //Get token        String token = ("token");
        // Get user agent        UserAgent userAgent = (().getHeader("User-Agent"));
        // Get ip        String ipaddr = (());
        // Get login location        String loginLocation = (ipaddr);
        // Get the browser        String browser = ().getName();
        // Get the operating system        String os = ().getName();
        TokenService bean = ();
        AuthenticationEntryPointImpl authenticationEntryPointImpl = ();
        // Verify whether the token is valid        Map&lt;String, Object&gt; stringObjectMap = (token);
        boolean bl = false;
        if (() &gt; 0) {
            // Get login information            LoginUser user = (LoginUser) ("user");
            // Determine whether the same computer, same browser, same operating system, same login location            if (user != null &amp;&amp; (()) &amp;&amp; (()) &amp;&amp; (()) &amp;&amp; (())) {
                bl = true;
            }
        }
        if(!bl){
            // Return error message when the verification fails - reuse the information of Spring Security framework            (request, response, null);
        }
        return bl;
    }
}

package ;

import ;
import ;
import ;
import ;
import ;

import .;
import .;
import ;
import ;
import ;

import com.;
import com.;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

import ;
import ;
import ;
import ;
import ;

/**
  * token verification processing
  *
  * @author hhxx
  */
@Component
public class TokenService
{
    // Token custom identification    @Value("${}")
    private String header;

    // Token key    @Value("${}")
    private String secret;

    // The token validity period (default 30 minutes)    @Value("${}")
    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;
    
    /***
      * Verify token
      * @param token
      * @return
      */
    public Map&lt;String,Object&gt; verifyToken(String token) {
    	
    	Map&lt;String,Object&gt; resultMap = new HashMap&lt;&gt;();
    	boolean bl = true;
    	try {
    		Claims claims = parseToken(token);
    		// parse the corresponding permissions and user information            String uuid = (String) (Constants.LOGIN_USER_KEY);
            String userKey = getTokenKey(uuid);
            LoginUser user = ((userKey),);
            if(user != null) {
            	bl = true;
            	("bl", bl);
            }else {
            	bl = false;
            	("bl", bl);
            	("msg", "Token has expired");
            }
    	}catch (ExpiredJwtException  eje) {
            bl = false;
            ("bl", bl);
        	("msg", "Token has expired");
    	}
    	catch(Exception ex) {
    		bl = false;
    		("bl", bl);
        	("msg", "Token verification exception");
    	}
    	
    	return resultMap;
    }
}

Summarize

This is the article about intercepting the vue front-end img access authentication backend. For more related content on img access authentication backend, please search for my previous article or continue browsing the following related articles. I hope everyone will support me in the future!