主管考慮到接口傳使用者名密碼不安全,是以讓接口驗證統一換成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結果展示
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiI0NXYFhGd192UvwVe0lmdhJ3ZvwFM38CXlZHbvN3cpR2Lc1TPB10QGtWUCpEMJ9CXsxWam9CXwADNvwVZ6l2c052bm9CXUJDT1wkNhVzLcRnbvZ2Lc5WNXlFc4dVYohmMjZXUYpVd1kmYr50MZV3YyI2cKJDT29GRjBjUIF2LcRHelR3LcJzLctmch1mclRXY39zNzMzMyUjM3EjMyEDM4EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)