Skip to content

Instantly share code, notes, and snippets.

@SuperHuangXu
Created January 6, 2018 09:34
Show Gist options
  • Save SuperHuangXu/9af35f604f1539c96d8613e976031c03 to your computer and use it in GitHub Desktop.
Save SuperHuangXu/9af35f604f1539c96d8613e976031c03 to your computer and use it in GitHub Desktop.
如何使用JWT?
'use strict';
const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();
const PORT = 4000;
// 可以fs.readfile...
const SECRET_KEY = 'secretkey123';
// 配置,expires:过期时间。
const jwtConfig = {expiresIn: '18s'};
app.get('/api', (req, res, next) => {
res.json({
message: 'Welcome to the API.',
});
});
app.post('/api/posts', verifyToken, (req, res) => {
jwt.verify(req.token, SECRET_KEY, (err, authData) => {
if (err) {
/* 如果token过期,err格式
* err = {
name: 'TokenExpiredError',
message: 'jwt expired',
expiredAt: '2018-01-01T13:23:25.000Z'
}
如果token验证错误,err格式
err = {
name: 'JsonWebTokenError',
message: 'invalid token'
}
* */
res.json({err});
res.sendStatus(403);
} else {
res.json({
message: 'Post created...',
authData,
});
}
});
});
app.post('/api/login', (req, res) => {
// Mock user
const user = {
id: 1,
username: '小明',
email: 'hello@qq.com',
};
// 获取token;
jwt.sign({user}, SECRET_KEY, jwtConfig, (err, token) => {
res.json({token});
});
});
// token格式
// Authorization: Bearer <access_token>
// 检验是否有Token
function verifyToken(req, res, next) {
// 获取authorization 的值
const bearerHeader = req.headers['authorization'];
// 检查如果bearer是否存在
if (typeof bearerHeader !== 'undefined') {
// 得到token
const token = bearerHeader.substr(8);
// 设置token
req.token = token;
// Next middleware
next();
} else {
// Forbidden //被禁止
res.sendStatus(403);
}
}
app.listen(PORT, function() {
console.log(`Server started on the port ${PORT}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment