标签:next value 出现 seo nal 字符串 过程 返回 auth
/** *实体类 */ public class User { private Integer id;//主键id private String userCode;//若是第三方登录,系统将自动生成唯一账号;自注册用户则为邮箱或者手机号 private String userPassword;//若是第三方登录,系统将自动生成唯一密码;自注册用户则为自定义密码 private String userType;//用户类型(标识:0 自注册用户 1 微信登录 2 QQ登录 3 微博登录) private String flatId;//平台ID(根据不同登录用户,进行相应存入:自注册用户主键ID、微信ID、QQID、微博ID) private Integer activated;//是否激活(0:否 1:是) public Integer getId() { return id; } public Integer getActivated() { return activated; } public void setActivated(Integer activated) { this.activated = activated; } public void setId(Integer id) { this.id = id; } public String getUserCode() { return userCode; } public void setUserCode(String userCode) { this.userCode = userCode; } public String getUserPassword() { return userPassword; } public void setUserPassword(String userPassword) { this.userPassword = userPassword; } public String getUserType() { return userType; } public void setUserType(String userType) { this.userType = userType; } public String getFlatId() { return flatId; } public void setFlatId(String flatId) { this.flatId = flatId; }
package com.kgc.utils.common; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Random; public class MD5 { public static String getMd5(String plainText,int length) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) { i += 256; } if (i < 16) { buf.append("0"); } buf.append(Integer.toHexString(i)); } // 32位 // return buf.toString(); // 16位 // return buf.toString().substring(0, 16); return buf.toString().substring(0, length); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } public static int getRandomCode(){ int max=9999; int min=1111; Random random = new Random(); return random.nextInt(max)%(max-min+1) + min; } public static void main(String[] args) { System.out.println(MD5.getMd5("helloadsfdsffsf",6)); System.out.println(getRandomCode()); } }
/** * 生成token * * @param User * @param userAgent 判断是移动端还是PC端 需要controller传入 HttpServletRequest request String userAgent = request.getHeader("user-agent"); * @return */ public String createToken(User ser, String userAgent) throws IOException { StringBuffer token=new StringBuffer(); token.append("token:"); UserAgentInfo userAgentInfo = UserAgentUtil.getUasParser().parse(userAgent); //获取访问设备并拼接 if(userAgentInfo.getDeviceType().equals(UserAgentInfo.UNKNOWN)){ if(UserAgentUtil.CheckAgent(userAgent)){ token.append("MOBILE-"); }else { token.append("PC-"); } }else if(userAgentInfo.getDeviceType().equals("Personal computer")){ token.append("PC-"); }else { token.append("MOBILE-"); } token.append(MD5.getMd5(ser.getUserCode(),32)+"-"); token.append(user.getId()+"-"); token.append(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+"-"); token.append(MD5.getMd5(userAgent,6)); return token.toString(); }
@RequestMapping(value = "/api") @RestController public class LoginController { @Resource private TokenService tokenService; /** * 用户登录 * * @param name * @param password * @return */ @RequestMapping(value = "/dologin", method = RequestMethod.POST, produces = "application/json") public Dto dologin(@RequestParam(value = "name") String name, @RequestParam(value = "password") String password, HttpServletRequest request) { try { String userAgent = request.getHeader("user-agent"); return tokenService.dologin(name, password,userAgent); } catch (Exception e) { e.printStackTrace(); return DtoUtil.returnFail("系统异常", ErrorCode.AUTH_UNKNOWN); } }
public interface TokenService { /** * 会话时间 */ public final static int SESSION_TIMEOUT=60*2*60; /** * 置换保护时间 */ public final static int REPLACETOKEN_PROTECTION_TIMEOUT=60*60; /** * 旧的token延迟时间 */ public final static int REPLACE=60*2; //用户登录 public Dto dologin(String userCode, String userPassword,String userAgent) throws Exception; //用户注销 public Dto logout(String token) throws Exception; //客户端置换token public Dto replacetoken(String token,String userAgent) throws Exception; }
@Service("LoginService") public class TokenServerImpl implements TokenService { @Resource private UserMapper UserMapper; @Resource private RedisAPI redisAPI; /** * 登录业务 * * @param userCode * @param userPassword * @return * @throws Exception */ @Override public Dto dologin(String userCode, String userPassword, String userAgent) throws Exception { Map<String, Object> userMap = new HashMap<>(); userMap.put("userCode", userCode); user user = userMapper.getListByMap(userMap).get(0); //用户是否存在 if (EmptyUtils.isNotEmpty(user)) { //判断用户密码是否正确 if (DigestUtil.hmacSign(userPassword, "kgc").equals(user.getUserPassword())) { String tokenString = createToken(user, userAgent); //存到缓存服务器中 redisAPI.set(tokenString, JSONObject.toJSONString(user)); System.out.println("tokenString=="+tokenString); //返回给前端 TokenVO tokenVO = new TokenVO(tokenString, Calendar.getInstance().getTimeInMillis() + SESSION_TIMEOUT * 1000, Calendar.getInstance().getTimeInMillis()); return DtoUtil.returnDataSuccess(tokenVO); } else { return DtoUtil.returnFail("用户密码错误", ErrorCode.AUTH_PARAMETER_ERROR); } } else { return DtoUtil.returnFail("用户不存在", ErrorCode.AUTH_USER_ALREADY_NOTEXISTS); } } @Override public Dto logout(String token) throws Exception { //删除服务端 redisAPI.del(token); return DtoUtil.returnSuccess(); } /** * 客户端置换token * @param token * @return * @throws Exception */ @Override public Dto replacetoken(String token,String userAgent) throws Exception { //判断token是否存在 if (!redisAPI.exists(token)){ return DtoUtil.returnFail("token不存在",ErrorCode.AUTH_TOKEN_INVALID); } String [] tokens=token.split("-"); SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMssHHmmss"); Date startDate=simpleDateFormat.parse(tokens[3]); String format=simpleDateFormat.format(new Date()); long logtime=simpleDateFormat.parse(format).getTime()-startDate.getTime(); if (logtime<REPLACETOKEN_PROTECTION_TIMEOUT*1000){ return DtoUtil.returnFail("token处于保护时间,禁止替换",ErrorCode.AUTH_REPLACEMENT_FAILED); } //以上情况都符合 User user=JSON.parseObject(redisAPI.get(token),User.class); //生成新的token String newtoken=createToken(user,userAgent); //覆盖新的请求,减少过期时间 redisAPI.set(token,JSONObject.toJSONString(user),REPLACE); redisAPI.set(newtoken,JSONObject.toJSONString(user),SESSION_TIMEOUT); //返回给前端 TokenVO tokenVO = new TokenVO(newtoken, Calendar.getInstance().getTimeInMillis() + SESSION_TIMEOUT * 1000, Calendar.getInstance().getTimeInMillis()); return DtoUtil.returnDataSuccess(tokenVO); } /** * 生成token * * @param User * @param userAgent 判断是移动端还是PC端 * @return */ public String createToken(User user, String userAgent) throws IOException { StringBuffer token=new StringBuffer(); token.append("token:"); UserAgentInfo userAgentInfo = UserAgentUtil.getUasParser().parse(userAgent); //获取访问设备并拼接 if(userAgentInfo.getDeviceType().equals(UserAgentInfo.UNKNOWN)){ if(UserAgentUtil.CheckAgent(userAgent)){ token.append("MOBILE-"); }else { token.append("PC-"); } }else if(userAgentInfo.getDeviceType().equals("Personal computer")){ token.append("PC-"); }else { token.append("MOBILE-"); } token.append(MD5.getMd5(user.getUserCode(),32)+"-"); token.append(user.getId()+"-"); token.append(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+"-"); token.append(MD5.getMd5(userAgent,6)); return token.toString(); } }
import org.springframework.stereotype.Component; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import javax.annotation.Resource; @Component public class RedisAPI { @Resource private JedisPool jedisPool; /** * 以键值对的方式保存数据到redis * * @param key * @param value */ public void set(String key, String value) { //获取连接 Jedis jedis = jedisPool.getResource(); try { String result = jedis.set(key, value); // 资源还回到连接池当中 //返还到连接池 jedisPool.returnResource(jedis); } catch (Exception e) { e.printStackTrace(); //销毁资源 jedisPool.returnBrokenResource(jedis); } } /** * 以键值对的方式保存数据到redis * * @param key * @param value * @param expire 时间 单位[秒] */ public void set(String key, String value, int expire) { //获取连接 Jedis jedis = jedisPool.getResource(); try { String result = jedis.setex(key, expire, value); // 资源还回到连接池当中 jedisPool.returnResource(jedis); } catch (Exception e) { e.printStackTrace(); //销毁资源 jedisPool.returnBrokenResource(jedis); } } /** * 取值 * * @param key */ public String get(String key) { //获取连接 Jedis jedis = jedisPool.getResource(); try { String result = jedis.get(key); // 资源还回到连接池当中 jedisPool.returnResource(jedis); return result; } catch (Exception e) { e.printStackTrace(); //销毁资源 jedisPool.returnBrokenResource(jedis); return null; } } /** * 获取剩余秒数 * * @param key */ public Long ttl(String key) { //获取连接 Jedis jedis = jedisPool.getResource(); try { Long result = jedis.ttl(key); // 资源还回到连接池当中 jedisPool.returnResource(jedis); return result; } catch (Exception e) { e.printStackTrace(); //销毁资源 jedisPool.returnBrokenResource(jedis); return null; } } /** * 判断key是否存在 * * @param key */ public Boolean exists(String key) { //获取连接 Jedis jedis = jedisPool.getResource(); try { System.out.println("key=========="+key); Boolean result = jedis.exists(key); // 资源还回到连接池当中 jedisPool.returnResource(jedis); return result; } catch (Exception e) { e.printStackTrace(); //销毁资源 jedisPool.returnBrokenResource(jedis); return false; } } /** * 删除 * * @param key */ public Long del(String key) { //获取连接 Jedis jedis = jedisPool.getResource(); try { Long result = jedis.del(key); // 资源还回到连接池当中 jedisPool.returnResource(jedis); return result; } catch (Exception e) { e.printStackTrace(); //销毁资源 jedisPool.returnBrokenResource(jedis); return null; } } }
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @ApiModel(value ="TokenVO",description = "用户认证凭证信息") public class TokenVO { @ApiModelProperty("用户认证凭据") private String token; @ApiModelProperty("过期时间,单位:毫秒") private long expTime; @ApiModelProperty("生成时间,单位:毫秒") private long genTime; public TokenVO() { } public TokenVO(String token, long expTime, long genTime) { this.token = token; this.expTime = expTime; this.genTime = genTime; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } public long getExpTime() { return expTime; } public void setExpTime(long expTime) { this.expTime = expTime; } public long getGenTime() { return genTime; } public void setGenTime(long genTime) { this.genTime = genTime; } }
/** * Token验证 * */ @Component public class ValidationToken { private Logger logger = Logger.getLogger(ValidationToken.class); private @Resource RedisAPI redisAPI; public RedisAPI getRedisAPI() { return redisAPI; } public void setRedisAPI(RedisAPI redisAPI) { this.redisAPI = redisAPI; } public ser getCurrentUser(String tokenString){ //根据token从redis中获取用户信息 /* test token: key : token:1qaz2wsx value : {"id":"100078","userCode":"myusercode","userPassword":"78ujsdlkfjoiiewe98r3ejrf","userType":"1","flatID":"10008989"} */ User ser = null; if(null == tokenString || "".equals(tokenString)){ return null; } try{ String userInfoJson = redisAPI.get(tokenString); ser = JSONObject.parseObject(userInfoJson,User.class); }catch(Exception e){ ser = null; logger.error("get userinfo from redis but is error : " + e.getMessage()); } return ser; } }
标签:next value 出现 seo nal 字符串 过程 返回 auth
原文地址:https://www.cnblogs.com/wangshuang123/p/11357071.html