Last active
October 27, 2018 11:57
-
-
Save loveyunk/4a1bc1ba2d6f31e0d6018b288f952ab5 to your computer and use it in GitHub Desktop.
jsonwebtoken例子
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment