java使用token防止用户重复登录以及验证用户登录

登录成功后,使用用户id构造生成一个token并保存到redis中,同时也保存用户id到session中

生成token的代码如下:

    @Override
    public String createToken(String phone,String appId) throws Exception {
        long loginTime = DateUtil.getNowTimeStampTime().getTime();
        String str = String.valueOf(phone) + CommonConstant.COMMA_CHARACTER+appId+ CommonConstant.COMMA_CHARACTER+ String.valueOf(loginTime);
        byte[] cipherData = null;
        String result = null;
        cipherData = RSAEncrypt.encrypt(Rsa2Manager.getPublicKeyGmall(), str.getBytes("UTF-8"));//RSA加密
        result = Base64.encode(cipherData);//加密
        return result;
    }

checkToken,获取当前session,有效则已登录,无效则获取当前的token,解密token,再去查询redis中的token是否有效,有效则再次对session赋值,还原登录状态

@Override
	public boolean isLogin(HttpSession session) throws Exception {
		boolean islogin = false;
		String appId = (String) session.getAttribute(UserConstant.LOGIN_APP_ID);
		String userId = (String) session.getAttribute(UserConstant.USER_SESSION_KEY);
		if (StringUtils.isNotBlank(appId) && StringUtils.isNotBlank(userId)) {
			islogin = true;
		} else {
			String phone ="";
			String appid ="";
			HttpServletRequest request = getCurrentThreadRequest();
			String currentToken = request.getHeader(CommonConstant.REQUEST_HEADER_TOKEN_NAME);
			if(StringUtils.isNotBlank(currentToken)){
				byte[] res = null;
				res = RSAEncrypt.decrypt(Rsa2Manager.getPrivateKeyGmall(), Base64.decode(currentToken));
				String restr = new String(res);
				String[] str = restr.split(",");
				phone = str[0];
				appid = str[1];
				String redisKey = CommonConstant.LOGIN_TOKEN.concat(phone);
				String token = RedisUtil.getRedisString(redisKey);
				if (StringUtils.isNotBlank(token)) {
					request.getSession().setAttribute(UserConstant.USER_SESSION_KEY, phone);
					request.getSession().setAttribute(UserConstant.LOGIN_APP_ID, appid);
					islogin = true;
				}else{
					islogin = false;
				}
			}
		}
		return islogin;
	}

  

posted on 2017-09-07 16:53  依米欧  阅读(10436)  评论(2编辑  收藏  举报