Multiple authentication types on the same route

In some cases I have API routes being accessed and sent a JWT token from a traditional applicatoin, but I also have some users accessing the same routes from tools such as python MatLab etc and would like them to be able to use an api token.

I could create multiple routes pointing to the same controller one handling jwt tokens and the other api tokens, but is there a way to have a single route which can handle both jwt and api tokens?

If I’m not mistaken, if you set the authentication middleware for those routes to auth rather than the more specific auth:jwt and so forth, it will allow users authenticated via any valid auth method to access that route.

Thank you, I will give it a try today.

Simon

@willvincent, that does not seem to work. in order to use a api token on a route, i had to use .middleware([‘auth:api’])

Is there any way to manually validate a jwt token? If there was, then I could remove the checking on the route and do it manually in the controller. I think I would be able to check the token first against the jwt authenticator, if that failed check it against the api authenticator and if both fail then I return a 403

Simon

OK, so I solved it. Not very elegant, but it works.

The important thing is to make sure you wrap your await statements in try/catch

It first checks if it can get a user using the jwt authenticator, if that user is null, it tries to get a user using the api authenticator.

try{
      var user = await auth.authenticator('jwt').getUser()
    }catch(err){
      console.log("jwt auth error", err)
    }
    if(!user){
      try{
        var user = await auth.authenticator('api').getUser()
      }catch(err){
        console.log("api auth error", err)
      }
    }

Looking at the auth middleware code, it looks like you could actually just provide the multiple auth methods you want to allow:

 * You can define one or multiple schemes to be tried.
 * ```
 * Route
 * .get('...')
 * .middleware('auth:basic,jwt')
 * ```
2 Likes