什么是Token?它有什么作用?怎么用?下面流程复制于网络上写得比较通俗易懂的一小段流程,在此就不在做重复的陈述!主要贴出代码 可以在项目中直接使用!
流程如下:
- 客户端使用用户名跟密码请求登录;
- 服务端收到请求,去验证用户名与密码;
- 验证成功后,服务端会签发一个 Token,再把这个 Token 发送给客户端;
- 客户端收到 Token 以后可以把它存储起来,比如放在 Cookie 里或者 Local Storage 里;
- 客户端每次向服务端请求资源的时候需要带着服务端签发的 Token;
- 服务端收到请求,然后去验证客户端请求里面带着的 Token,如果验证成功,就向客户端返回请求的数据。
Servers层:
1 |
public TokenEntity chekcToken(String token_content,String user_name,String uuid) throws Exception; |
Dao层
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
public TokenEntity chekcToken(String token_content,String user_name,String uuid) throws Exception { // 检查是否有token if (token_content != null && !"".equals(token_content)) { // 如果有直接返回查询结果 return commonService.singleResult(" from TokenEntity where username ='" + user_name + "' and tokencontent ='"+ token_content + "' and islosing = '0' "); } else { // 没有token // 先根据用户名和uuid查有效token,查到返回,查不到 新增。 TokenEntity tokens = commonService.singleResult("from TokenEntity where username ='"+user_name + "' and uuid ='"+ uuid + "' and islosing = '0' "); if (tokens != null) { return tokens; } TokenEntity token = new TokenEntity(); token.setAging(NumUtil.toInteger(parameterService.getParam(0, 0,"APP-TOKEN保存周期", "5", "APP-TOKEN保存周期,单位为天,默认5天"))); Long nowTime = DateUtils.getDate().getTime(); token_content = RemoteJSONSerializer.compressData(nowTime+ "#" + token.getUuid() + "#" + token.getUsername()); token.setTokencontent(token_content); token.setUsername(user_name); token.setCreatedtime(DateUtils.getDate()); token.setLosetime(DateUtils.getDateAdd(DateUtils.getDate(),token.getAging())); token.setIslosing("0"); commonService.save(token); return token; } } |