如何使用token儲存使用者登入資訊

2021-09-25 17:46:46 字數 2118 閱讀 8641

登入成功之後,後台生成乙個token,將token儲存在redis中,key是token,value是使用者id,並且把token響應給前端,前端每次請求時都把token傳給後台進行鑑權。生成token**如下:

/*** 校驗裝置資訊

* @param userid 使用者id

* @param deviceid 裝置id

*/public void checkdeviceinfo(long userid,string deviceid)

string key = authconstant.teacher_device_key+userid;

//如果裝置已註冊到redis中,判斷當前裝置是否可用

if(usersysredis.hashhaskey(key,deviceid)));

if(objects.isnull(deviceinfo))

if(devicestatusenum.alter_password.equals(deviceinfo.getdevicestatus()))

return;

}//如果未註冊,則新增到redis中

teacherdeviceinfo teacherdeviceinfo = new teacherdeviceinfo()

.setdeviceid(deviceid)

.setdevicestatus(devicestatusenum.normal_status);

usersysredis.hashput(key,deviceid,teacherdeviceinfo);

}}自定義***繼承handlerinterceptoradapter,在裡面實現登入校驗邏輯。邏輯是前端請求頭傳入token的值,後台拿到token後去redis中取,如果取到說明登入了,未取到說明沒登入,跳轉至登入頁。

配置鑑權***,交給spring管理:

/**

* 教師端鑑權***配置

* @author liuzhihao

* @date 2018/7/24

*/@configuration

@slf4j

public class authorizeconfiguration extends webmvcconfigureradapter

@override

public void addinterceptors(interceptorregistry registry)

}

介面方法:

public responseupdate(

@pathvariable("transferid") long transferid, @requestparam long classid,@requestparam integer status)

使用token方法儲存使用者登入狀態的實踐

錯誤示範 使用者登入後,使用 localstorage 方法在瀏覽器客戶端直接儲存 user id,每次進入 時,通過識別 user id 自動獲取使用者的資訊並實現登入。錯誤點瀏覽器 localstorage 儲存的資料可能被 篡改 在瀏覽器控制台使用 localstorage.setitem 即...

DRF 使用者登入加 token

實現 使用者登入成功後,對應的 token 表建立一條對應登入使用者的 token 資料 models.py from django.db import models class userinfo models.model user type choices 1,普通使用者 2,管理員 3,超級使用...

Redis妙用 儲存使用者token

在設計類似電商的系統時,乙個常見的需求是每個頁面都需要攜帶登入使用者資訊。常見的解決方法有兩種 使用cookie儲存 使用jwt儲存。但如果系統中使用了redis快取,那麼還可以有第三種解決方案 將使用者token快取在redis中。一 登陸時生成乙個token存入redis 生成乙個token物件...