전후 단 분리 token 권한 부여 로그 인 크로스 도 메 인 문제 해결

6547 단어 자바
   
package com.zy.interceptor;


import com.zy.annotation.Login;
import com.zy.common.exception.RRException;
import com.zy.entity.TokenEntity;
import com.zy.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 chenshun
 * @email [email protected]
 * @date 2018-08-01 15:38
 */
@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 {
        //    CORS
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "POST,OPTIONS,PUT,HEAD");
//        response.addHeader("Access-Control-Allow-Headers", "*");
        response.addHeader("Access-Control-Max-Age", "3600000");
        response.addHeader("Access-Control-Allow-Credentials", "true");
        response.addHeader("Access-Control-Allow-Headers", "Authentication,Origin, X-Requested-With, Content-Type, Accept,token");
        //   ,    ,
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);

        if (request.getMethod().equals("OPTIONS"))
            response.setStatus(HttpServletResponse.SC_OK);

        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("token");
        //  header    token,       token
        if(StringUtils.isBlank(token)){
            token = request.getParameter("token");
        }

        //token  
        if(StringUtils.isBlank(token)){
            throw new RRException("token    ");
        }

        //  token  
        TokenEntity tokenEntity = tokenService.queryByToken(token);
        System.out.println(tokenEntity.getExpireTime().getTime());
        System.out.println( System.currentTimeMillis());
        System.out.println(tokenEntity.getExpireTime().getTime() < System.currentTimeMillis());
        if(tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()){
            throw new RRException("token  ,     ");
        }

        //  userId request ,    userId,      
        request.setAttribute(USER_KEY, tokenEntity.getUserId());

        return true;
    }

token 서비스 계층 구현 클래스
package com.zy.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.zy.dao.TokenDao;
import com.zy.entity.TokenEntity;
import com.zy.service.TokenService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;


@Service("tokenService")
public class TokenServiceImpl extends ServiceImpl implements TokenService {
   /**
    * 12     
    */
   private final static int EXPIRE = 3600 * 12;

   @Override
   public TokenEntity queryByToken(String token) {
      return this.selectOne(new EntityWrapper().eq("token", token));
   }

   @Override
   public TokenEntity createToken(long userId) {
      //    
      Date now = new Date();
      //    
      Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

      //  token
      String token = generateToken();

      //       token
      TokenEntity tokenEntity = new TokenEntity();
      tokenEntity.setUserId(userId);
      tokenEntity.setToken(token);
      tokenEntity.setUpdateTime(now);
      tokenEntity.setExpireTime(expireTime);
      this.insertOrUpdate(tokenEntity);

      return tokenEntity;
   }

   @Override
   public void expireToken(long userId){
      Date now = new Date();

      TokenEntity tokenEntity = new TokenEntity();
      tokenEntity.setUserId(userId);
      tokenEntity.setUpdateTime(now);
      tokenEntity.setExpireTime(now);
      this.insertOrUpdate(tokenEntity);
   }

   private String generateToken(){
      return UUID.randomUUID().toString().replace("-", "");
   }
}

 
token 실체 클래스
package com.zy.entity;

import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.IdType;

import java.io.Serializable;
import java.util.Date;



/**
 *   Token
 * 
 * @author chenshun
 * @email [email protected]
 * @date 2018-08-01 15:22:07
 */
@TableName("tb_token")
public class TokenEntity implements Serializable {
   private static final long serialVersionUID = 1L;

   /**
    *   ID
    */
   @TableId(type=IdType.INPUT)
   private Long userId;
   private String token;
   /**
    *     
    */
   private Date expireTime;
   /**
    *     
    */
   private Date updateTime;

   /**
    *   :  ID
    */
   public void setUserId(Long userId) {
      this.userId = userId;
   }
   /**
    *   :  ID
    */
   public Long getUserId() {
      return userId;
   }
   /**
    *   :token
    */
   public void setToken(String token) {
      this.token = token;
   }
   /**
    *   :token
    */
   public String getToken() {
      return token;
   }
   /**
    *   :    
    */
   public void setExpireTime(Date expireTime) {
      this.expireTime = expireTime;
   }
   /**
    *   :    
    */
   public Date getExpireTime() {
      return expireTime;
   }
   /**
    *   :    
    */
   public void setUpdateTime(Date updateTime) {
      this.updateTime = updateTime;
   }
   /**
    *   :    
    */
   public Date getUpdateTime() {
      return updateTime;
   }
}

좋은 웹페이지 즐겨찾기