天天看点

接口Token设计实现

 主管考虑到接口传用户名密码不安全,所以让接口验证统一换成Token,设计开发过程整理如下:

1、设计思路:

 考虑到后期权限验证在token实体类增加了用户名;

 通过调用接口获取token对象,对象放到缓存或Map中;

 验证token前清理过期的token对象;

2Token类

public class TokenEntity {
	
	private String token; //token 
	
	private String userName; //用户名
	
	private Long expiresIn; //有效期  秒
	
	private Date createDate;  //创建时间
 // …………
}
           

3TokenCache类

/**
      * 获取Token列表
      * @return
      */
     public static List<TokenEntity> getActiveTokenEntityList(){
		return getCache().getList(ACTIVE_LIST_KEY);
     }
     /**
      * 获取token对象
      * @param code
      * @return
      */
     public static TokenEntity getTokenEntityByToken(String code){
    	 return (TokenEntity) getCache().get(code);
     }
    /**
     * 获取用户名     
     * @param code
     * @return
     */
     public static String getUserNameByToken(String code){
    	 TokenEntity token = getTokenEntityByToken(code);
    	 if(token == null){
    		 return null;
    	 }
    	 return token.getUserName();
     }
     /**
      * 放入缓存
      * @param token
      */
     public static void tokenPut(TokenEntity token) {
    	 getCache().put(token.getToken(), token);
    	 List<TokenEntity> activeList = getActiveTokenEntityList();
    	 if(activeList == null) {
    		 activeList = new ArrayList<TokenEntity>();
    	 }
    	 activeList.add(token);
    	 getCache().put(ACTIVE_LIST_KEY, activeList);
     }
     /**
      * 刷新缓存(清理失效token)
      */
	@Override
	public void refreshCache() throws Exception {
		PageHelper.clearPage();
		List<TokenEntity> all = getActiveTokenEntityList();
		
		List<TokenEntity> invalidList = new ArrayList<TokenEntity>();
		Date current = new Date();
		for(TokenEntity p: all){
			long pass = (current.getTime()-p.getCreateDate().getTime())/1000;	//转化秒		
			if(pass > p.getExpiresIn()) {
				invalidList.add(p);
				getCache().delete(p.getToken());
			}			
		}
		all.removeAll(invalidList);
		getCache().put(ACTIVE_LIST_KEY, all);
	}
           

4、在接口中使用

/**
	 * 主数据下载
	 * @param response
	 * @param request
	 * @throws Exception
	 */
	@RequestMapping(value="/masterDataDownload.do")
	public void masterDataDownload(HttpServletResponse response, HttpServletRequest request) throws Exception {		
		String token = request.getParameter("Token");
		String bu = request.getParameter("BU");
		WfLogger.info("============masterDataDownload=======token=============="+token+ "---" +bu);
		String tokenMsg = CacheUtils.loginTokenValidate(token);
		if(!StringUtil.isEmpty(tokenMsg)){
			AjaxUtil.ajaxReturn(AjaxUtil.rtnMapJson(ReturnMsgAndCode.TOKEN_ISEMTPY_CODE,tokenMsg,null),response);
			return;
		}
		ProductUpload model = new ProductUpload();
		List<ProductUpload> list = commonService.selectList(model);
		AjaxUtil.ajaxReturn(AjaxUtil.rtnMapJson(ReturnMsgAndCode.SUCCESS_CODE,ReturnMsgAndCode.SUCCESS_DOWNLOAD_MESSAGE,list),response);
		return;
	}
           

5结果展示

接口Token设计实现