Token驗證登錄狀態(tài)的簡單實現(xiàn)

設(shè)計思路

  1. 用戶發(fā)出登錄請求您朽,帶著用戶名和密碼到服務(wù)器經(jīng)行驗證铸史,服務(wù)器驗證成功就在后臺生成一個token返回給客戶端
  2. 客戶端將token存儲到cookie中举庶,服務(wù)端將token存儲到redis中怒坯,可以設(shè)置存儲token的有效期掀淘。
  3. 后續(xù)客戶端的每次請求資源都必須攜帶token旬蟋,這里放在請求頭中,服務(wù)端接收到請求首先校驗是否攜帶token革娄,以及token是否和redis中的匹配倾贰,若不存在或不匹配直接攔截返回錯誤信息(如未認證)。
  • token管理:生成拦惋、校驗匆浙、解析、刪除

  • token:這里使用userId_UUID的形式

  • 有效期:使用Redis key有效期設(shè)置(每次操作完了都會更新延長有效時間)

  • 銷毀token:刪除Redis中key為userId的內(nèi)容

  • token存儲:客戶端(Cookie)厕妖、服務(wù)端(Redis)

  • Cookie的存取操作(jquery.cookie插件)

  • Redis存仁啄帷(StringRedisTemplate)

實現(xiàn)

完整代碼可到springboot2.x整合redis實現(xiàn)簡單的token登錄鑒權(quán)中下載
(本demo只是個小例子,還有很多不足,用于實際環(huán)境還需要根據(jù)實際考慮更多的問題)

【Redis操作類】

package com.bpf.tokenAuth.utils;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class RedisClient {
    
    public static final long TOKEN_EXPIRES_SECOND = 1800;

    @Autowired
    private StringRedisTemplate redisTpl;
    
    /**
     * 向redis中設(shè)值
     * @param key 使用 a:b:id的形式在使用rdm進行查看redis情況時會看到分層文件夾的展示形式,便于管理
     * @param value
     * @return
     */
    public boolean set(String key, String value) {
        boolean result = false;
        try {
            redisTpl.opsForValue().set(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    
    
    /**
     * 向redis中設(shè)置言秸,同時設(shè)置過期時間
     * @param key
     * @param value
     * @param time
     * @return
     */
    public boolean set(String key, String value, long time) {
        boolean result = false;
        try {
            redisTpl.opsForValue().set(key, value);
            expire(key, time);
            result =  true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    
    /**
     * 獲取redis中的值
     * @param key
     * @return
     */
    public String get(String key) {
        String result = null;
        try {
            result = redisTpl.opsForValue().get(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
  
    }
    
    /**
     * 設(shè)置key的過期時間
     * @param key
     * @param time
     * @return
     */
    public boolean expire(String key, long time) {
        boolean result = false;
        try {
            if(time > 0) {
                redisTpl.expire(key, time, TimeUnit.SECONDS);
                result = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    
    /**
     * 根據(jù)key刪除對應(yīng)value
     * @param key
     * @return
     */
    public boolean remove(String key) {
        boolean result = false;
        try {
            redisTpl.delete(key);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    
    
    
    
}

【Token管理類】

package com.bpf.tokenAuth.utils.token;

import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.bpf.tokenAuth.utils.RedisClient;

@Component
public class RedisTokenHelp implements TokenHelper {
    
    @Autowired
    private RedisClient redisClient;

    @Override
    public TokenModel create(Integer id) {
        String token = UUID.randomUUID().toString().replace("-", "");
        TokenModel mode = new TokenModel(id, token);
        redisClient.set(id == null ? null : String.valueOf(id), token, RedisClient.TOKEN_EXPIRES_SECOND);
        return mode;
    }

    @Override
    public boolean check(TokenModel model) {
        boolean result = false;
        if(model != null) {
            String userId = model.getUserId().toString();
            String token = model.getToken();
            String authenticatedToken = redisClient.get(userId);
            if(authenticatedToken != null && authenticatedToken.equals(token)) {
                redisClient.expire(userId, RedisClient.TOKEN_EXPIRES_SECOND);
                result = true;
            }
        }
        return result;
    }

    @Override
    public TokenModel get(String authStr) {
        TokenModel model = null;
        if(StringUtils.isNotEmpty(authStr)) {
            String[] modelArr = authStr.split("_");
            if(modelArr.length == 2) {
                int userId = Integer.parseInt(modelArr[0]);
                String token = modelArr[1];
                model = new TokenModel(userId, token);
            }
        }
        return model;
    }

    @Override
    public boolean delete(Integer id) {
        return redisClient.remove(id == null ? null : String.valueOf(id));
    }

}

【攔截器邏輯】

package com.bpf.tokenAuth.interceptor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.bpf.tokenAuth.annotation.NoneAuth;
import com.bpf.tokenAuth.constant.NormalConstant;
import com.bpf.tokenAuth.entity.JsonData;
import com.bpf.tokenAuth.utils.JsonUtils;
import com.bpf.tokenAuth.utils.token.TokenHelper;
import com.bpf.tokenAuth.utils.token.TokenModel;

@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {
    
    @Autowired
    private TokenHelper tokenHelper;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println(11);
        // 如果不是映射到方法直接通過
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //如果被@NoneAuth注解代表不需要登錄驗證软能,直接通過
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        if(method.getAnnotation(NoneAuth.class) != null) return true;       
        //token驗證
        String authStr = request.getHeader(NormalConstant.AUTHORIZATION);
        TokenModel model = tokenHelper.get(authStr);
        
        //驗證通過
        if(tokenHelper.check(model)) {
            request.setAttribute(NormalConstant.CURRENT_USER_ID, model.getUserId());
            return true;
        }
        //驗證未通過
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.getWriter().write(JsonUtils.obj2String(JsonData.buildError(401, "權(quán)限未認證")));
        return false;
    }
}

【登錄邏輯】

package com.bpf.tokenAuth.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.bpf.tokenAuth.annotation.NoneAuth;
import com.bpf.tokenAuth.constant.MessageConstant;
import com.bpf.tokenAuth.constant.NormalConstant;
import com.bpf.tokenAuth.entity.JsonData;
import com.bpf.tokenAuth.entity.User;
import com.bpf.tokenAuth.enums.HttpStatusEnum;
import com.bpf.tokenAuth.mapper.UserMapper;
import com.bpf.tokenAuth.utils.token.TokenHelper;
import com.bpf.tokenAuth.utils.token.TokenModel;

@RestController
@RequestMapping("/token")
public class TokenController {
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private TokenHelper tokenHelper;
    
    @NoneAuth
    @GetMapping
    public Object login(String username, String password) {
        User user = userMapper.findByName(username);
        if(user == null || !user.getPassword().equals(password)) {
            return JsonData.buildError(HttpStatusEnum.NOT_FOUND.getCode(), MessageConstant.USERNAME_OR_PASSWORD_ERROR);
        }
        //用戶名密碼驗證通過后,生成token
        TokenModel model = tokenHelper.create(user.getId());
        return JsonData.buildSuccess(model);    
    }
    
    @DeleteMapping
    public Object logout(HttpServletRequest request) {
        Integer userId = (Integer) request.getAttribute(NormalConstant.CURRENT_USER_ID);
        if(userId != null) {
            tokenHelper.delete(userId);
        }
        return JsonData.buildSuccess();
    }

}

測試

【login.html】


<!DOCTYPE html>
<html>  
<head>
<title>Login</title>
<link rel="stylesheet" href="../res/css/login.css">
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/jquery-cookie/1.4.1/jquery.cookie.js"></script>
</head>
<body>
    <form>
        <input type="text" name="username" id="username">
        <input type="password" name="password" id="password">
    </form>
    <input type="button" value="Login" onclick="login()">
</body>
<script type="text/javascript">
function login(){
    $.ajax({
        url: "/tokenAuth/token",
        dataType: "json",
        data: {'username':$("#username").val(), 'password':$("#password").val()},
        type:"GET",
        success:function(res){
            console.log(res);
            if(res.code == 200){
                var authStr = res.data.userId + "_" + res.data.token;
                //把生成的token放在cookie中
                $.cookie("authStr", authStr);
                window.location.href = "index.html";
            }else alert(res.msg);
        }
    });
}
</script>
</html>

【index.html】


<!DOCTYPE html>
<html>  
<head>
<title>Index</title>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/jquery-cookie/1.4.1/jquery.cookie.js"></script>
</head>
<body>
    <input type="button" value="Get" onclick="get()">
    <input type="button" value="logout" onclick="logout()">
</body>
<script type="text/javascript">

function get(){
    $.ajax({
        url: "/tokenAuth/user/bpf",
        dataType: "json",   
        type:"GET",
        beforeSend: function(request) {
            //將cookie中的token信息放于請求頭中
            request.setRequestHeader("authStr", $.cookie('authStr'));
        },
        success:function(res){
            console.log(res);
        }
    });
}

function logout(){
    $.ajax({
        url: "/tokenAuth/token",
        dataType: "json",   
        type:"DELETE",
        beforeSend: function(request) {
            //將cookie中的token信息放于請求頭中
            request.setRequestHeader("authStr", $.cookie('authStr'));
        },
        success:function(res){
            console.log(res);
        }
    });
}
</script>
</html>

測試環(huán)境中兩個頁面login.html和index.html均當做靜態(tài)資源處理
【未登錄狀態(tài)】

【登錄狀態(tài)】

  • 訪問登錄網(wǎng)站http://localhost:8080/tokenAuth/page/login.html查排,輸入username和password進行點擊Login按鈕登錄
  • 登錄成功并跳轉(zhuǎn)到index頁面,并且生成cookie抄沮,這里沒有設(shè)置cookie有效期跋核,默認關(guān)閉瀏覽器失效


  • 再次點擊get按鈕請求數(shù)據(jù),請求成功


  • 點擊logout按鈕銷毀登錄狀態(tài)叛买,然后再次請求數(shù)據(jù)


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末砂代,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子率挣,更是在濱河造成了極大的恐慌刻伊,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,378評論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件椒功,死亡現(xiàn)場離奇詭異捶箱,居然都是意外死亡,警方通過查閱死者的電腦和手機蛾茉,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,970評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來撩鹿,“玉大人谦炬,你說我怎么就攤上這事。” “怎么了键思?”我有些...
    開封第一講書人閱讀 168,983評論 0 362
  • 文/不壞的土叔 我叫張陵础爬,是天一觀的道長。 經(jīng)常有香客問我吼鳞,道長看蚜,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,938評論 1 299
  • 正文 為了忘掉前任赔桌,我火速辦了婚禮供炎,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘疾党。我一直安慰自己音诫,他們只是感情好,可當我...
    茶點故事閱讀 68,955評論 6 398
  • 文/花漫 我一把揭開白布雪位。 她就那樣靜靜地躺著竭钝,像睡著了一般。 火紅的嫁衣襯著肌膚如雪雹洗。 梳的紋絲不亂的頭發(fā)上香罐,一...
    開封第一講書人閱讀 52,549評論 1 312
  • 那天,我揣著相機與錄音时肿,去河邊找鬼庇茫。 笑死,一個胖子當著我的面吹牛嗜侮,可吹牛的內(nèi)容都是我干的港令。 我是一名探鬼主播,決...
    沈念sama閱讀 41,063評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼锈颗,長吁一口氣:“原來是場噩夢啊……” “哼顷霹!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起击吱,我...
    開封第一講書人閱讀 39,991評論 0 277
  • 序言:老撾萬榮一對情侶失蹤淋淀,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后覆醇,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體朵纷,經(jīng)...
    沈念sama閱讀 46,522評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,604評論 3 342
  • 正文 我和宋清朗相戀三年永脓,在試婚紗的時候發(fā)現(xiàn)自己被綠了袍辞。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,742評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡常摧,死狀恐怖搅吁,靈堂內(nèi)的尸體忽然破棺而出威创,到底是詐尸還是另有隱情,我是刑警寧澤谎懦,帶...
    沈念sama閱讀 36,413評論 5 351
  • 正文 年R本政府宣布肚豺,位于F島的核電站,受9級特大地震影響界拦,放射性物質(zhì)發(fā)生泄漏吸申。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 42,094評論 3 335
  • 文/蒙蒙 一享甸、第九天 我趴在偏房一處隱蔽的房頂上張望截碴。 院中可真熱鬧,春花似錦枪萄、人聲如沸隐岛。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,572評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽聚凹。三九已至,卻和暖如春齐帚,著一層夾襖步出監(jiān)牢的瞬間妒牙,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,671評論 1 274
  • 我被黑心中介騙來泰國打工对妄, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留湘今,地道東北人。 一個月前我還...
    沈念sama閱讀 49,159評論 3 378
  • 正文 我出身青樓剪菱,卻偏偏與公主長得像摩瞎,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子孝常,可洞房花燭夜當晚...
    茶點故事閱讀 45,747評論 2 361