基于拦截器对token 进行时间校验

    1. 主要是需要继承 HandlerInterceptorAdapter类重写拦截器方法进行逻辑处理 ```java /**
      • Copyright (c) 2016-2019 人人开源 All rights reserved. *
      • https://www.renren.io *
      • 版权所有,侵权必究! */

    package io.renren.interceptor;

    import io.renren.annotation.Login; import io.renren.common.exception.RRException; import io.renren.entity.TokenEntity; import io.renren.service.TokenService; import org.apache.commons.lang.StringUtils; 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 javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

    /**

    • 权限(Token)验证 *
    • @author Mark sunlightcs@gmail.com */ @Component public class AuthorizationInterceptor extends HandlerInterceptorAdapter { @Autowired private TokenService tokenService;

      public static final String USER_KEY = “userId”;

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

      1. Login annotation;
      2. if(handler instanceof HandlerMethod) {
      3. annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
      4. }else{
      5. return true;
      6. }
      7. if(annotation == null){
      8. return true;
      9. }
      10. //从header中获取token
      11. String token = request.getHeader("token");
      12. //如果header中不存在token,则从参数中获取token
      13. if(StringUtils.isBlank(token)){
      14. token = request.getParameter("token");
      15. }
      16. //token为空
      17. if(StringUtils.isBlank(token)){
      18. throw new RRException("token不能为空");
      19. }
      20. //查询token信息
      21. TokenEntity tokenEntity = tokenService.queryByToken(token);
      22. if(tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()){
      23. throw new RRException("token失效,请重新登录");
      24. }
      25. //设置userId到request里,后续根据userId,获取用户信息
      26. request.setAttribute(USER_KEY, tokenEntity.getUserId());
      27. return true;

      } }

    ```