主頁 > 知識庫 > 基于redis實現(xiàn)token驗證用戶是否登陸

基于redis實現(xiàn)token驗證用戶是否登陸

熱門標簽:Linux服務器 服務外包 百度競價排名 網(wǎng)站排名優(yōu)化 呼叫中心市場需求 鐵路電話系統(tǒng) 地方門戶網(wǎng)站 AI電銷

基于項目需求, 我們要實現(xiàn)一個基于redis實現(xiàn)token登錄驗證,該如何實現(xiàn)呢:

后端實現(xiàn):

1.引入redis相關(guān)的依賴

dependency>
 groupId>org.springframework.boot/groupId>
 artifactId>spring-boot-starter-data-redis/artifactId>
/dependency>
dependency>
 groupId>org.springframework.session/groupId>
 artifactId>spring-session-data-redis/artifactId>
 version>2.0.5.RELEASE/version>
/dependency>

2.Controller層生成token信息并存入redis中

//若用戶登錄驗證成功后將對應的登陸信息和登陸憑證一起存入redis中
//生成登陸憑證token UUID
String uuidToken= UUID.randomUUID().toString();
uuidToken=uuidToken.replace("-","");
 
//將token和用戶登錄態(tài)之間建立聯(lián)系
redisTemplate.opsForValue().set(uuidToken,userModel);
redisTemplate.expire(uuidToken,1, TimeUnit.HOURS);
 
// 下發(fā)token
return CommonReturnType.create(uuidToken);

3.需要驗證的登陸的地方調(diào)用即可

 String token = httpServletRequest.getParameterMap().get("token")[0];
 if (StringUtils.isEmpty(token)) {
 throw new BusinessException(EmBusinessError.USER_NOT_LOGIN, "用戶還未登陸,不能下單");
 }
 //獲取用戶的登陸信息
 UserModel userModel= (UserModel) redisTemplate.opsForValue().get(token);
 if(userModel==null){
 throw new BusinessException(EmBusinessError.USER_NOT_LOGIN, "用戶還未登陸,不能下單");
 }
 
 OrderModel orderModel = orderService.creatOrder(userModel.getId(), itemId, promoId, amount);
 return CommonReturnType.create(null);

前端實現(xiàn)

1.從返回值中取出token并存入localstorage

if(data.status == "success") {
 alert("登陸成功");
 //取出token放入localstorage
 var token = data.data;
 window.localStorage["token"] = token;
 window.location.href = "listitem.html";
}

2.驗證用戶是否登陸

var token = window.localStorage["token"];
 if(token == null){
 alert("沒有登錄,不能下單");
 window.location.href="login.html" rel="external nofollow" ;
 return false;
 } 

3.當然,需要把token傳入后端再校驗一次

url:"http://"+g_host+"/order/createorder?token="+token,

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

您可能感興趣的文章:
  • PHP+Redis 消息隊列 實現(xiàn)高并發(fā)下注冊人數(shù)統(tǒng)計的實例
  • 利用Redis統(tǒng)計網(wǎng)站在線活躍用戶的方法
  • PHP使用redis實現(xiàn)統(tǒng)計緩存mysql壓力的方法
  • Redis中統(tǒng)計各種數(shù)據(jù)大小的方法
  • redis 實現(xiàn)登陸次數(shù)限制的思路詳解
  • redis開啟和禁用登陸密碼校驗的方法
  • 基于Redis位圖實現(xiàn)系統(tǒng)用戶登錄統(tǒng)計

標簽:湘潭 衡水 黃山 湖南 崇左 蘭州 仙桃 銅川

巨人網(wǎng)絡通訊聲明:本文標題《基于redis實現(xiàn)token驗證用戶是否登陸》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡,涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266