第一次登錄時會返回一個通過加密的token,下一次訪問接口(攜帶登陸返回你的token)的時候,會對token進行解密,若是解密正在進行,說明你已經登陸,再把過時時間延長
npm init -y // 一鍵初始化 npm install express -s // 下載express npm install cors // 跨域中間件 npm install body-parser // body-parser中間件 解析帶請求體的數據(post,put) npm install jsonwebtoken // 持久化登陸 jwt json web token
// 引入express let 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})) // listen 後面跟着的是端口 app.listen(8000,function(){ console.log('OK') })
app.post('/login',function(req,res){ let {username} = req.body console.log(username) res.json({ // 進行加密的方法 // sing 參數一:加密的對象 參數二:加密的規則 參數三:對象 token:jwt.sign({username:username},'abcd',{ // 過時時間 expiresIn:"1h" }), username, code:200 }) })
postMan模擬 發送POST請求前端
接收到數據web
獲得tokenexpress
把 token 寫入headernpm
// 登陸持久化驗證接口 訪問這個接口的時候 必定要訪問token(前端頁面每切換一次,就訪問一下這個接口,問一下我有沒有登陸/登錄過時) // 先訪問登陸接口,獲得token,在訪問這個,看是否成功 app.post('/validate',function(req,res){ // 訪問 token let token = req.headers.authorization; // console.log(token) // 驗證token合法性 對token進行解碼,解碼方式要和加密方式同樣 jwt.verify(token,'abcd',function(err,decode){ if(err){ res.json({ msg:'當前用戶未登陸' }) }else { // 證實用戶已經登陸 res.json({ username:decode.username, msg:'已登陸' }) token:jwt.sign({username:decode.username},'abcd',{ // 過時時間 expiresIn:"1h" }) } }) })
已有登陸帳號,持久化登陸成功json
token:jwt.sign({username:decode.username},'abcd',{ // 若是過時時間爲1秒 expiresIn:"1s" })
得到 token跨域
設置頭部信息服務器
驗證 過時時間生效app