Testing with JWT validation middleware

So I am implementing a PHP-based API with middleware that checks for the presence of, and verifies JWT access tokens sent via the Authorization request header. The middleware uses the Auth0 PHP SDK to verify and decode the JWT token, and it works great.

However, I’m not sure how to do automated testing of the API endpoints without having to contact Auth0 to get a token. The only thing I can come up with is either disabling the middleware during testing or somehow mock out the token verification (leaving the middleware enabled).

I’m a little paranoid about having some kind of mechanism to disable or skip the middleware, since I want to be sure it cannot be bypassed in production through misconfiguration or other means.

Is there a recommended approach to this? Any ideas or pointers?

Hi @marcusb

Almost never do I say this, but in this case ROPG will help. Use Resource Owner Password Grant to get a token for testing purposes.

John

Hi @john.gateley

I haven’t tried that, but I think I found another solution:

The API uses a dependency injection container that allows me to switch from the token verifier implementation used by the middleware.

The middleware constructor takes a \Auth0\SDK\Helpers\Tokens\TokenVerifier and the DI container is normally configured to inject an asymmetric token verifier (\Auth0\SDK\Helpers\Tokens\AsymmetricVerifier). When testing, I simply override the DI container definition to inject a symmetric token verifier instead (\Auth0\SDK\Helpers\Tokens\SymmetricVerifier).

This allows me to create an entirely customized and valid (or invalid!) token using a hardcoded issuer, audience and secret. As far as I know, there is no way for someone to accidentally enable this behaviour outside of testing (and even if there was I won’t deploy the test suite to production anyway).

Actually, I just realized that the same approach could be used to just replace the JWK in the AssymetricVerifier during tests using a fake key :laughing:

Hi @marcusb

That sounds great! Thanks for posting the information here, it will help others.

John