Bearer Authorization - andrewkyllo-401-advanced-javascript/seattle-javascript-401d34 GitHub Wiki

Bearer Authorization

  • Following a signin attempt using either basic authentication or OAuth, your service is able to make a boolean decision as to the success of the attempt.
  • Bearer tokens are encoded JSON objects that contain enough information for the server to assert that any client request that presents a valid token must have originated from a client that has previously authenticated themselves using either basic or oauth.
  • Bearer tokens are sent to the user/client after the initial singin process has completed
  • Clients must make every subsequent request to the server with that token, in the header
    • Authorization: Bearer encoded.jsonwebtoken.here
  • The server opens the token, does the re-authentication, and then grants or denies access
  • In express servers, this can be done in middleware, in conjunction with a user model
app.get('/somethingsecret', bearerToken, (req,res) => {
  res.status(200).send('secret sauce');
});

function bearerToken( req, res, next ) {
  let token = req.headers.authorization.split(' ').pop();
  try {
    if ( tokenIsValid(token) ) { next(); }
  }
  catch(e) { next("Invalid Token") }
}

function tokenIsValid(token) {
  let parsedToken = jwt.verify(token, SECRETKEY);
  return Users.find(parsedToken.id);
}