前后分离项目,

1.自定义注解

package com.as.common.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 
 * @Description 手机端Token验证,使用此注解会验证Token有效性及合法性
 *                   拦截器com.as.common.config.MobileLoginConfig
 * @author 张银彪 
 * @category
 * @date 2020年2月27日 下午1:35:19 
 * @version V0.1
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Login {

}

2.拦截器

package com.as.common.interceptor;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSONObject;
import com.as.common.annotation.Login;
import com.as.common.constant.Constant;
import com.as.common.constant.HttpRequestConst;
import com.as.common.utils.R;
import com.as.common.utils.Result;
import com.as.modules.security.dao.SysUserTokenDao;
import com.as.modules.security.entity.SysUserTokenEntity;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

/**
 * 
 * @Description 手机端登录验证Token合法性 添加@Login注解进入拦截,次拦截器只有对/api/**URL生效
 * @author 张银彪 
 * @category
 * @date 2020年2月28日 下午1:57:11 
 * @version V0.1
 */
@Component
public class TokenValidata extends HandlerInterceptorAdapter {
    public final Logger logger=Logger.getLogger("Token校验");;
       @Autowired
        protected SysUserTokenDao sysUserTokenDao;
    public static final String USER_KEY = "userId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        response.setContentType("application/json;charset=UTF-8");
        try {
            Login annotation;
            if(handler instanceof HandlerMethod) {
                annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
            }else{
                return true;
            }
            if(annotation == null){
                return true;
            }
    
            //从header中获取token
            String token = request.getHeader(Constant.TOKEN_HEADER);
            String userid = request.getHeader(Constant.USER_ID_HEADER);
            //如果header中不存在token,则从参数中获取token
            if(StringUtils.isBlank(token)||StringUtils.isBlank(userid)){
                //未传入token userid
                Result<Object> error = R.error(HttpRequestConst.UNAUTHORIZED, "不是合法操作");
                String jsonString = JSONObject.toJSONString(error);
                ServletOutputStream outputStream = response.getOutputStream();
                outputStream.write(jsonString.getBytes());
                    return false;
            }

            //判断是否生成过token
            QueryWrapper<SysUserTokenEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("token", token);
            wrapper.eq("user_id", userid);
            SysUserTokenEntity selectOne = sysUserTokenDao.selectOne(wrapper);
            //判断token是否过期
            logger.info("当前登录用户:"+selectOne.getUserId());
            logger.info("Token:"+selectOne.getToken());
            logger.info("Token过期时间:"+selectOne.getExpireDate());
            if(selectOne.getExpireDate().getTime() < System.currentTimeMillis()){
                response.setStatus(HttpStatus.SC_UNAUTHORIZED);
                
                Result<Object> error = R.error(HttpRequestConst.UNAUTHORIZED, "登录失效,请重新登录");
                String jsonString = JSONObject.toJSONString(error);
                ServletOutputStream outputStream = response.getOutputStream();
                outputStream.write(jsonString.getBytes());
                return false;//不进入方法
            }
            return true;//放行
        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.setStatus(HttpStatus.SC_UNAUTHORIZED);
                Result<Object> error = R.error(HttpRequestConst.UNAUTHORIZED, "登录失效,请重新登录(ERR)");
                String jsonString = JSONObject.toJSONString(error);
                ServletOutputStream outputStream = response.getOutputStream();
                outputStream.write(jsonString.getBytes());
            } catch (IOException e1) {
                  return false;
                }
                response.setStatus(HttpStatus.SC_UNAUTHORIZED);
              return false;
        }
    }
    
    
}

3.使用

    @PostMapping("/updateUserInfo")
    @ApiOperation(value = "更新微信用户的信息")
    @Login // 进行Token的合法性,有效性验证
    public Result updateUserInfo(@RequestBody XcWxUserDTO xcWxUserDTO) {
        xcWxUserService.update(xcWxUserDTO);
        return R.success();
    }