Custom github JWT Auth with Redwood Auth

Show and tell!
So managed to make the code a lot cleaner today, and also implemented “access key” style auth alongside jwt. This is so that we can support the web client (redwood) and a cli. We needed a way to revoke this access key, and had no need for a transparent token, which we generate in one of the services and save to DB.

Only a couple of changes:

node_modules/@redwoodjs/api/dist/auth/authHeaders.js
Modify the default case statement to simply return an unrecognised auth provider’s token, instead of throwing an error. We can just as easily use “custom” as the key here, but I wanted both JWT and an opaque token.

.
.
.
    case 'auth0':
      {
        decoded = await (0, _verifyAuth0Token.verifyAuth0Token)(token);
        break;
      }

    default:
      decoded = {
        type,
        token
      }
      break;
.
.
.

src/lib/auth.js
Moved the logic for validating the token into getCurrentUser. Note the case statement to check the type of token

.
.
`// This function gets called on every auth required call
// to populate context.currentUser
// NOTE: I've patched package to return the undecoded token as TokenHeader

// TokenHeader = {
// type: 'cli' | 'jwt',
// token: 'xxxyyyzzz'
// }

export const getCurrentUser = async (tokenHeader) => {
  let user
  let decodedJwt

  const { token, type } = tokenHeader

  switch (type) {
    case 'jwt':
      decodedJwt = jwt.verify(token, JWT_PUBLIC_KEY)
      user = await findUser({
        email: decodedJwt.email,
      })
      break

    case 'cli':
      user = await CliToken.userFromToken({
        token,
      })
      break

    default:
      throw new AuthenticationError()
  }

  return user
}
.
.

Et viola!


More than happy to jump in an a conversation on Github if you’d like Peter - very happy to be contributing back. I can also clean this up, and create a public repo if it’s easier to follow the code that way.