Web and Mobile Development: Server Side Authentication

Bill Mongan

Authentication

  • Java Web Tokens (jwt)
header.payload.signature
  • Header: boilerplate information about the signature algorithm
  • Payload: The actual key information
  • Signature: The digital signature is the header and payload signed with a private key
  • Each element is Base-64 encoded

Authentication

  • If you authenticate a user, you can send them a jwt containing a JSON document of their username.
  • They provide that key back to you on each request.
  • You can verify the key by decrypting the signature with your public key and matching it against the payload.

Creating a jwt in node.js

const jwt = require("jsonwebtoken")
const token = jwt.sign({ username }, "secret key", { algorithm: "HS256", expiresIn: 300});

If authentication fails:

return res.status(401).end(); // unauthorized

Verifying a jwt in node.js

const jwt = require("jsonwebtoken")
// obtain token from body request or cookie
payload = jwt.verify(token, "secret key"); 
// try/catch the above to return an HTTP error should validation fail

If authentication fails:

return res.status(401).end(); // unauthorized

Generating a Secret Key to Sign

// https://www.digitalocean.com/community/tutorials/nodejs-jwt-expressjs
const crypto = require('crypto');
crypto.randomBytes(64).toString('hex'); // export this environment variable
  • Get the secret via process.env.TOKEN_SECRET;

  • Once generated, the jwt can be passed as a header, or a cookie, or a body parameter.

Using the jwt

  • Once you validate the jwt, you know that you must have generated it (why?)
  • You can Base-64 decode the middle component (split on “.”) to obtain the payload structure, including the user ID or other information you generated