JWT is pronounced "jot". Yeah.
Securely transmit JSON between two parties
It's a JSON Object that has been encrypted & stored in a particular way
Most people use it for Authentication
It's small enough to fit inside an HTTP Header
Contains everything we need to know about the user
xxxxx.
yyyyy.
zzzzz
Header
Payload
Signature
{
"alg": "HS256",
"typ": "JWT"
}
"alg" : Short for "Algorithm"
"typ" : is always "JWT"
{
"sub": "1234567890",
"name": "John Doe",
"admin": true
}
var jwt = require("jsonwebtoken");
var token = jwt.sign({name:"Liz"},"super-top-secret-string-of-secrets");
var t = jwt.decode(token,"super-top-secret-string-of-secrets");
console.log(t);
To generate:
To decode:
Set the header:
res.setHeader("Authorization","Bearer "+ token);
function checkToken(req,res,next){
try {
var decoded = jwt.verify(req.headers.authorization.split(" ")[1], secret);
if(req.params.id && decoded.id === req.params.id){
req.decoded_id = decoded.id;
next();
}
else {
res.status(401).send("Not Authorized");
}
} catch(err) {
res.status(500).send(err.message);
}
}
router.use(checkHeaders);