Skip to content

Instantly share code, notes, and snippets.

@ianaya89
Created November 28, 2019 19:35
Show Gist options
  • Save ianaya89/251d364689310bae7c1e2e35791c85a5 to your computer and use it in GitHub Desktop.
Save ianaya89/251d364689310bae7c1e2e35791c85a5 to your computer and use it in GitHub Desktop.

REST Authentication with JWT

inline 80%


πŸ‡¦πŸ‡· Nacho Anaya

inline


inline 50%

^ I will use the help of thinking face


πŸ€” Why token authentication?


πŸ€” Why token authentication?

> Stateless

^ 1. The server does not have to keep a record ^ 2. No server session


πŸ€” Why token authentication?

> Decoupled

^ 1. Token could be issued for other server. ^ 2. Perfect for cross domain (no cookies)


πŸ€” Why token authentication?

> Scalable

^ 1. Reduce data look up ^ horizontally scale ^ No client session


πŸ€” Why JWT?


πŸ€” Why JWT?

> Standard RFC 7519

^ 1. Base on web standard RFC 7519 ^ Defines A safe way to represent a set of information between two parties


πŸ€” Why JWT?

> Self Contained

^ 2. All the info is inside (transmit information)


πŸ€” Why JWT?

> Compact

^ 3. NO XML, lighter content


πŸ€” Why JWT?

> Signed

^ 4. Cryptographic Signed ^ Keeps token secure ^ Allows to validate against modifications ^ Hashed message or public/private key pairs


πŸ€” Why JWT?

> JSON πŸ™Œ

^ 5. Easy to read and parse, humans and machines


πŸ€” What is JWT?

^ Token based on encoded JSON


πŸ€” What is JWT?

+ Base64

^ Is composed by tree base64 Parts, separated by dots


πŸ€” What is JWT?

inline


πŸ’† Header

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

^ type & algoritm, In this cases hashed message


πŸ‘Œ Payload

{
  "id": "1234567890",
  "name": "John Doe",
  "admin": true,
  "iss": "https://api.com",
  "exp": 1510745797148
}

^ claims, information to exchange public claims


πŸ‘Œ Payload

{
  "id": "1234567890",
  "name": "John Doe",
  "admin": true,
  "iss": "https://api.com",
  "exp": 1510745797148
}

^ reserved claims


✍️ Signature

const data = base64urlEncode( header ) + '.' +
  base64urlEncode( payload )

HMACSHA256(data, 'your_secret_message')

^ encoded header & payload + secret (encrypted) ^ proves identity ^ ensure message can't change


✍️ Signature

const data = base64urlEncode( header ) + '.' +
  base64urlEncode( payload )

HMACSHA256(data, 'your_secret_message')


πŸ€” When to use it?


πŸ€” When to use it?

> Authentication

> Information Exchange


πŸ€” Where to use it?


πŸ€” Where to use it?

SPA's - Mobile

Serverless - IoT

^ AI OU TI



πŸ₯

^ drums sound


πŸ‘ REST API's


πŸ€” How does it work with REST?



πŸ€” How does it work with REST?

1. Sends Credentials

POST /login

{
	"user": "ianaya89",
	"password": "dont-hack-me"
}

πŸ€” How does it work with REST?

2. Creates JWT

const jwt = require('jsonwebtoken')

// POST /login
function login (req, res, next) {
  // Validates user credentials...

  const payload = { user: 'ianaya89', role: 'admin' }

  const token = jwt.sign(payload, 'this_is_super_secret')
  res.status(201).send({ token: `Bearer ${token}` })
}

router.post('/login', login)

πŸ€” How does it work with REST?

3. Returns JWT

const jwt = require('jsonwebtoken')

// POST /login
function login (req, res, next) {
  // Validates user credentials...

  const payload = { user: 'ianaya89', role: 'admin' }

  const token = jwt.sign(payload, 'this_is_super_secret')
  res.status(201).send({ token: `Bearer ${token}` })
}

router.post('/login', login)

^ The client should save / persist the token


πŸ€” How does it work with REST?

4. Gets a resource

GET /resource
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiIxMjM0NTY3ODkiLCJuYW1lIjoiSm9obiBEb2UiLCJhZG1pbiI6ZmFsc2V9.
b99O1RrYbHtWJ3MGZXkdADZkmiLm9HNliRccKxMPDuc

^ Access protected endpoint, The client should save / persist the token


πŸ€” How does it work with REST?

5. Verifies token

const jwt = require('jsonwebtoken')

// GET /resource
function getResource (req, res, next) {
  try {
    const payload = jwt.verify(token, 'this_is_super_secret')
  }
  catch (err) {
     return res.sendStatus(401)
  }
}

router.get('/resource', getResource)

^ middleware, automatization


πŸ€” How does it work with REST?

6. Sends response

const jwt = require('jsonwebtoken')

// GET /resource
function getResource (req, res, next) {
  try {
    const payload = jwt.verify(token, 'this_is_super_secret')
    res.send('πŸ‘Œ')
  }
  catch (err) {
     return res.sendStatus(401)
  }
}

router.get('/resource', getResource)

πŸ€” How does it work with REST?

6. Sends response

const jwt = require('jsonwebtoken')

// GET /resource
function getResource (req, res, next) {
  try {
    const payload = jwt.verify(token, 'this_is_super_secret')

    if (payload.role !== 'admin') {
      return res.sendStatus(403)
    }

    res.send('πŸ‘Œ')
  }
  catch (err) {
     return res.sendStatus(401)
  }
}

router.get('/resource', getResource)

πŸ€” Which languages are supported?


πŸ€” Which languages are supported?

> "All" of them


πŸ€” Is JWT secure?


πŸ₯

^ drums sound


πŸ€” Is JWT secure?

πŸ‘Œ Yes


πŸ€” Is JWT secure?

🀭 But...

^ there is always a but


^ Forest's mom said


πŸ€” Is JWT secure?

> Anyone can view the content

^ Don't store sensitive information


πŸ€” Is JWT secure?

> No one can modify it


πŸ€” Is JWT secure?

> JWT is signed not ecnrpyted

^ JSON Web Encryption allows you to safely encrypt the claims of a token


πŸ€” Is JWT secure?

> Keep your "secret" secret 😏


πŸ“š Resources


πŸ‘•


πŸ‘ Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment