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;
	}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM