vue

Vue axios请求头设置参数token验证权限

2018-12-27  本文已影响0人  tangtangdd

1 前端代码  

axios.defaults.baseURL ='http://192.168.1.147:8090'

axios.defaults.timeout =6000

axios.interceptors.request.use(

config => {

// config.headers['Content-Type'] = 'application/x-www-form-urlencoded';

        let token =localStorage.getItem('token')

if (token) {

config.headers.common['token'] =localStorage.getItem('token');

}

return config

},

err => {

return Promise.reject(err);

}

)

2 登录的时候把Token 写入本地存储

localStorage.setItem('token',this.encryptionDesc)

3 后端请求设置跨域

一 设置拦截规则

package com.real2tech.virtualTeach.config;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.web.servlet.HandlerInterceptor;

import org.springframework.web.servlet.config.annotation.InterceptorRegistry;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration

public class WebAppConfigurerextends WebMvcConfigurationSupport {

// addPathPatterns 用于添加拦截规则

    // excludePathPatterns 用户排除拦截

    @Bean

    public HandlerInterceptor getMyInterceptor(){

return new FilterIPActionInterceptor();

}

@Override

    public void addInterceptors(InterceptorRegistry registry) {

registry.addInterceptor(getMyInterceptor())

.addPathPatterns("/**").

excludePathPatterns("/user/login");

}

}

二 跨域配置设置

package com.real2tech.virtualTeach.config;

import org.springframework.stereotype.Component;

import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

@Component

public class CORSFilterextends OncePerRequestFilter {

static final StringORIGIN ="Origin";

public  void doFilterInternal(

HttpServletRequest request,

HttpServletResponse response,

FilterChain filterChain)throws ServletException, IOException {

String origin = request.getHeader(ORIGIN);

response.setHeader("Access-Control-Allow-Origin","*");//* or origin as u prefer

        response.setHeader("Access-Control-Allow-Credentials","true");

response.setHeader("Access-Control-Allow-Methods","PUT, POST, GET, OPTIONS, DELETE");

response.setHeader("Access-Control-Max-Age","3600");

response.setHeader("Access-Control-Allow-Headers","content-type, token");

if (request.getMethod().equals("OPTIONS")) {

response.setStatus(HttpServletResponse.SC_OK);

}else{

filterChain.doFilter(request, response);

}

}

}

三 拦截器配置

*结合自己业务的加密方式  以及其他要求

package com.real2tech.virtualTeach.config;

import com.real2tech.virtualTeach.entity.ManageUser;

import com.real2tech.virtualTeach.mapper.ManageUserMapper;

import com.real2tech.virtualTeach.utils.TokenUits;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;

import org.springframework.stereotype.Service;

import org.springframework.web.servlet.HandlerInterceptor;

import org.springframework.web.servlet.ModelAndView;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@Component

@Service

public class FilterIPActionInterceptorimplements HandlerInterceptor {

private static Loggerlogger = LoggerFactory.getLogger(HandlerInterceptorAdapter.class);

@Autowired

    private ManageUserMappermanageUserMapper;

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)

throws Exception {

logger.info("request请求地址path[{}] uri[{}]", request.getServletPath(),request.getRequestURI());

String url = request.getRequestURI();

if (url.contains("/user/login")) {

return true;

}

String  token = request.getHeader("token");

String userId = TokenUits.JudgementToken(token);

ManageUser manageUser =manageUserMapper.selectById(userId);

if (null != manageUser) {

//            QueryWrapper queryWrapper = new QueryWrapper();

//            queryWrapper.eq("te_id", manageUser.getUserId());

//            List list = userEncryptionMapper.selectList(queryWrapper);

//            if (null != list && list.size() > 0) {

                if (token.equals(manageUser.getEncryptionDesc())) {

return true;

}else {

throw new Exception("请确认你的权限");

}

//            }

        }

return false;

}

@Override

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,

ModelAndView modelAndView)throws Exception {}

@Override

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)

throws Exception {

}

}

以上只为实现 比较简单 勿喷  亲测可行  

上一篇下一篇

猜你喜欢

热点阅读