JSON Web Tokens

JWT is pronounced "jot". Yeah.

JSON Web Tokens

  • What is a JWT
  • Why do I use this
  • How do I use it

Objectives:

What is JWT?

Securely transmit JSON between two parties

What is JWT?

What is JWT?

It's a JSON Object that has been encrypted & stored in a particular way

Most people use it for Authentication

JWT: Why

Compact

It's small enough to fit inside an HTTP Header

Self-Contained

Contains everything we need to know about the user

JWT: Take a look

xxxxx.

yyyyy.

zzzzz

Header

Payload

Signature

JWT Header

{
  "alg": "HS256",
  "typ": "JWT"
}

"alg" : Short for "Algorithm"

"typ" : is always "JWT"

JWT Payload: Your Data

{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true
}

Generating JWTs

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);

Verifying JWTs

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);

Login with JWT

TOGETHER!

JSON Web Tokens

By LizTheDeveloper

JSON Web Tokens

  • 1,381