Custom github JWT Auth with Redwood Auth

@morganmspencer and @edjiang FYI I’ve opened an issue:

and referenced this post.

Thanks again for pointing this out!

2 Likes

Thanks for the help! Was code reading and it seems like the interface for a Client is straightforward especially due to the type annotations. But definitely was confused at that step :slight_smile:

1 Like

Got a basic prototype working. Only feedback on documentation was that it was not intuitive that you had to add an auth-provider: custom header in the HTTP request in order for Redwood’s stack to even check the access token and call my handlers. Such a requirement is unintuitive for non-Redwood callers like mobile apps (although not a huge deal).

1 Like

@edjiang Great to hear! Also, would you be up for improving the documentation based on your experience? And/or creating a related issue with your notes and suggestions for improvement would be great as well.

No pressure at all but 100% welcome:

There’s a certain amount of polish needed to write docs on GH, but what I can do to help is write a summary here and add a link in the GH

Build auth endpoint into the api project:

Write the SDL

In my case I was building phone auth stored in the local database. Design your SDL and put it in /api/src/graphql/auth.sdl.js

# Passwordless example
type Mutation {
  authChallenge(input: AuthChallengeInput!): AuthChallengeResult
  authVerify(input: AuthVerifyInput!): AuthVerifyResult # Should return a token
}

# Username/password example
type Mutation {
  authRegister(input: AuthRegisterInput!): AuthRegisterResult
  authLogin(input: AuthLoginInput!): AuthLoginResult # Should return a token
  authVerify(input: AuthVerifyInput!): AuthVerifyResult
  authForgotPassword(input: AuthForgotPasswordInput!): AuthForgotPasswordResult
}

Write the Service

In /api/src/services/auth/auth.js

export const authChallenge = async (input) => { return { success: true } }
// ...etc

Write a token validator and user resolver

In /api/src/lib/auth.js:

import { AuthenticationError } from '@redwoodjs/api'

export const getCurrentUser = async (token) => {
  // Resolve and return user record
}

export const requireAuth = () => {
  if (!context.currentUser) {
    throw new AuthenticationError("You don't have permission to do that.")
  }
}

Add the user resolver to the GraphQL endpoint

In /api/src/functions/graphql.js:

import { getCurrentUser } from 'src/lib/auth' // Add this line

export const handler = createGraphQLHandler({
  getCurrentUser, // Add this line
  schema: makeMergedSchema({
    schemas,
    services: makeServices({ services }),
  }),
  onException: () => {
    // Disconnect from your database with an unhandled exception.
    db.$disconnect()
  },
})

Authenticate via HTTP Headers!

Add Authorization: Bearer TOKEN and replace TOKEN with your token value
Add Auth-Provider: custom

Viola! You should be able to authenticate using a custom provider now.

Implement Frontend Client

I haven’t implemented this, but you’ll also need to implement the UI to hit your backend endpoints.

3 Likes

Thanks for this auth blueprint @edjiang

Just so readers know why this is – that the authProvider type is sent in the headers along with the Bearer token – is that different authentication providers have different ways of decoding (or not decoding) the access token.

While many will decode and verify the JWT, some (like Netlify Identity) has the token already decoded in its own context

and verified and some like Auth0 need to ]get a signing key in order to verify the token](https://github.com/redwoodjs/redwood/blob/1d7973d8315eb940b9504ca5eccb0567ce235eed/packages/api/src/auth/decoders/auth0.ts#L40):

So, the set of decoders needs to know which one applies – hence passed in the headers.

While I understand that in this implementation it’s necessary, most likely it would make sense to have two bits of configuration, the getCurrentUser and tokenMiddleware or something instead of declaratively using the auth-provider.

For most apps you won’t be using multiple providers, and declaring a tokenMiddleware that decodes the token will allow developers to flexibly handle incoming authorization and types.

True – while “apps” may not, multiple different “sides” could.

One may one day implement a cli side that needs to interact differently than the web side to authenticate. Ie - it might send an API_TOKEN that is connected to a user/team/project account to authenticate.

But, I see your point. Redwood always welcomes PRs or issues to make the framework better, more useful, and a cleaner DX, so if you’d like to submit an approach I’m sure the community there can definitely discuss and see if that can happen.

FYI - this example is from 2020 and there is in RedwoodJS v2+ a new way.

See the docs here about using auth in serverless functions: Serverless Functions | RedwoodJS Docs

import type { APIGatewayEvent, Context } from 'aws-lambda'

import { useRequireAuth } from '@redwoodjs/graphql-server'

import { getCurrentUser, isAuthenticated } from 'src/lib/auth'
import { logger } from 'src/lib/logger'

const myHandler = async (event: APIGatewayEvent, context: Context) => {
  logger.info('Invoked myHandler')

  if (isAuthenticated()) {
    logger.info('Access myHandler as authenticated user')

    return {
      statusCode: 200,
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        data: 'myHandler function',
      }),
    }
  } else {
    logger.error('Access to myHandler was denied')

    return {
      statusCode: 401,
    }
  }
}

export const handler = useRequireAuth({
  handlerFn: myHandler,
  getCurrentUser,
})