loveyunk
10/27/2018 - 11:28 AM

jwt.js

jsonwebtoken例子

var express = require('express');
var jwt = require('jsonwebtoken');

const app = express();

app.get('/api', function (req, res) {
  res.json({
    text: 'my api!'
  });
});

app.post('/api/login', function (req, res) {
  // auth user
  const user = { id: 3 };
  const token = jwt.sign({ user }, 'my_secret_key');
  res.json({
    token
  });
});

app.get('/api/protected', ensureToken, function (req, res) {
  jwt.verify(req.token, 'my_secret_key', function (err, data) {
    if (err) {
      res.sendStatus(403);
    } else {
      res.json({
        text: 'this is protected',
        data
      });
    }
  });
});

function ensureToken (req, res, next) {
  const bearerHeader = req.headers['authorization'];
  console.log(bearerHeader);
  if (typeof bearerHeader !== 'undefined') {
    const bearer = bearerHeader.split(' ');
    const bearerToken = bearer[1];
    req.token = bearerToken;
    next()
  } else {
    res.sendStatus(403);
  }
}

app.listen(3300, function () {
  console.log('App listening on port 3300');
});