在計算機身份認證中是令牌(臨時)的意思,在詞法分析中是標記的意思。通常咱們所說的的 token 大可能是指用於身份驗證的 tokenjavascript
先安裝第三方模塊 jsonwebtoken npm install jsonwebtoken
前端
const express = require('express') const path = require('path') const app = express(); const bodyParser = require('body-parser'); const jwt = require('jsonwebtoken'); app.use(bodyParser.urlencoded({extended: false})); app.use(express.static(path.join(__dirname, '/'))); app.all('*', function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Auth, Accept,X-Requested-With"); res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS"); res.header("X-Powered-By",' 3.2.1') if(req.method=="OPTIONS") { res.sendStatus(200);/*讓options請求快速返回*/ } else{ next(); } }); app.get('/createtoken', (request, response) => { //要生成 token 的主題信息 let user = { username: 'admin', } //這是加密的 key(密鑰) let secret = 'dktoken'; //生成 Token let token = jwt.sign(user, secret, { 'expiresIn': 60*60*24 // 設置過時時間, 24 小時 }) response.send({status: true, token}); }) app.post('/verifytoken', (request, response) => { //這是加密的 key(密鑰),和生成 token 時的必須同樣 let secret = 'dktoken'; let token = request.headers['auth']; if(!token){ response.send({status: false, message: 'token不能爲空'}); } jwt.verify(token, secret, (error, result) => { if(error){ response.send({status: false}); } else { response.send({status: true, data: result}); } }) }) app.listen(88)
$.ajax({ url: 'verifytoken', type: 'post', headers: {"auth": 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiaWF0IjoxNTIzNTQwNjY5LCJleHAiOjE1MjM2MjcwNjl9.ddkS5XEiMzvNQsk9UlMPhyxPSq5S_oh3Nq19eIm9AJU'}, success: function(res){ console.log(res) } })
var xhr = new XMLHttpRequest(); xhr.open("POST","verifytoken"); xhr.setRequestHeader('auth', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiaWF0IjoxNTIzNTQwNjY5LCJleHAiOjE1MjM2MjcwNjl9.ddkS5XEiMzvNQsk9UlMPhyxPSq5S_oh3Nq19eIm9AJU'); xhr.send();
import axios from 'axios' axios({ url: url, params: _params || {}, headers: {auth: window.sessionStorage.getItem('dktoken')} }).then(res => { if(!res.data.status && res.data.error == "unauthorized"){ router.push('login'); return false; } resolve(res) }).catch(error => { reject(error) })
import http from 'superagent' http.post(getUrl(path)) .set('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8') .set('auth', window.localStorage.getItem('access_token')) .end((err, res) => {});