jwt 持久化驗證前端篇,node 配置詳情請移步這里
我用的是vue3,下面是 src 的目錄

用到的依賴

驗證思路
Home 頁寫登錄,然后在 About 頁獲取到登錄名。
登錄成功緩存 token,進入About頁時,通過判斷是否有 token 來判斷是否登錄/登錄超時
登錄頁
在登錄頁輸入用戶名和密碼,將其提交到vuex
// src/views/Home.vue<template> <div class="home"> <input type="text" v-model="user" placeholder="賬號"> <input type="text" v-model="password" placeholder="密碼"> <button @click="login">點擊</button> </div></template><script>import {mapActions} from 'vuex'export default { data(){ return{ user:'', password:'' } }, name: 'home', methods:{ ...mapActions(["toLogin"]), login(){ // 請求之后能拿到用戶名,nickname,把用戶名存在state // 傳入多個參數 改成對象 // action moutation只能拿第一個參數哦,所以要改成對象 this.toLogin({user:this.user,password:this.password}) } }}</script>后臺 jwt
后臺的 jwt 驗證,我們把過期時間設置成60s
// src/app.jslet express = require('express')let cors = require('cors')let bodyParser = require('body-parser')let jwt = require("jsonwebtoken")let app = express()app.use(cors())app.use(bodyParser.json())app.use(bodyParser.urlencoded({extended:false}))// 模擬一個登陸的接口app.post('/login',function(req,res){ // 登錄成功獲取用戶名 let username = req.body.user res.json({ // 進行加密的方法 // sing 參數一:加密的對象 參數二:加密的規則 參數三:對象 token:jwt.sign({username:username},'abcd',{ // 過期時間 expiresIn:"60s" }), username, code:200 })})// 登錄持久化驗證接口 訪問這個接口的時候 一定要訪問token(前端頁面每切換一次,就訪問一下這個接口,問一下我有沒有登錄/登陸過期)// 先訪問登錄接口,得到token,在訪問這個,看是否成功app.post('/validate',function(req,res){ let token = req.headers.authorization; // 驗證token合法性 對token進行解碼 jwt.verify(token,'abcd',function(err,decode){ if(err){ res.json({ msg:'當前用戶未登錄' }) }else { // 證明用戶已經登錄 res.json({ token:jwt.sign({username:decode.username},'abcd',{ // 過期時間 expiresIn:"60s" }), username:decode.username, msg:'已登錄' }) } })})app.listen(8000,function(){ console.log('OK')})后臺接口
// src/api/login.jsimport axios from 'axios'axios.defaults.baseURL = 'http://localhost:8000'// axios 請求攔截axios.interceptors.request.use(function(response){ // 在 headers 中設置authorization 屬性放token,token是存在緩存中的 response.headers.authorization = localStorage["token"] return response}, function (error) { return Promise.reject(error); })// axios 響應攔截器axios.interceptors.response.use(function (response) { return response.data; }, function (error) { return Promise.reject(error); });// 登錄的接口export let loginApi = (user,password) => { return axios.post('/login',{user,password})}// 驗證是否登錄的接口export let valiApi = () => { return axios.post('/validate')}vuex
// src/store.jsimport Vue from 'vue'import Vuex from 'vuex'Vue.use(Vuex)import {loginApi,valiApi} from './api/login'export default new Vuex.Store({ state: { username:"" }, mutations: { setusername(state,payload){ // 改變state里的 username state.username = payload } }, actions: { async toLogin({commit},{user,password}){ let res = await loginApi(user,password) console.log(res) let {username,token} = res // 提交到 mutations commit("setusername",username) // token 具有時效性 登錄成功 把token存在本地存儲 localStorage["token"] = token }, async valiApi({commit}){ const { username, token } = await valiApi(); commit('setusername', username); localStorage["token"] = token return username !== undefined; } }})驗證持久化登錄頁
從 vuex 中拿到用戶名,打開頁面就請求是否登錄的 api ,從而實現持久化登錄驗證
// src/views/About.vue<template> <div class="about"> 昵稱:{{nickname}} </div></template><script>import {mapState} from "vuex"import {valiApi} from '../api/login'export default { data(){ return{ nickname:'' } }, computed:{ ...mapState(["username"]) }, // 打開這個頁面 就請求 valiApi 查看用戶是否登錄 async created(){ let res = await valiApi(); console.log(res) this.nickname = res.username if(res.username !== undefined){ alert("welcome " + res.username) } else { alert("請登錄") } }}</script>操作 驗證是否成功
運行 node

登錄
點擊登錄按鈕,登錄成功,成功獲取到用戶名和token

驗證
由于我們設置的過期時間是60s,所以要在60s內點擊About頁查看

60s后(過期后)

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答