Skip to content
Advertisement

How to correctly set a JWT secret in Laravel with jwt-auth?

I’d like to test the authentication of JWTs in my project as the JWTs will be sent from outside the app, and so they must be signed using the key from my application. Is this possible? Does anyone know of a site that allows you to sign a token using a secret?

I tried http://jwtbuilder.jamiekurtz.com/ but JWT-auth keeps returning {"error":"token_invalid"} if I enter the key which was returned by jwt:generate. This leads me to believe the key returned by this command is not actually the key used to sign JWTs in my application.

I’m using php artisan jwt:generate to generate a key, which returns the following:

jwt-auth secret [...] set successfully.

But where is it set? The JWT_SECRET variable in my .ENV file doesn’t change, and if I perform a project wide search for the key it’s not found.

Does this command work?

Laravel 5.3, jwt-auth 0.5.9.

Advertisement

Answer

Recent testing in both 0.5.9 and 0.5.12 indicates that the jwt:generate command ONLY changes the value in config/jwt.php IFF it is the key in use. To see this for yourself, set the value in .env to be the same as in config/jwt.php and it WILL change the one in config the first time you run it but then it will break.

A bit of searching indicates that the dev has no plans to fix this for 0.5.*

I wrote a (admittedly rather ungainly single line) bash script that will create this JWT_SECRET in .env if it does not exist or update all occurrences of ‘JWT_SECRET=’:

env=".env"; secret="$(php artisan jwt:generate --show)"; oldsecrets="$(grep '^JWT_SECRET=' $env)"; if [ -z "$oldsecrets" ]; then sed -i "$ a JWT_SECRET=$secret" "$env"; else echo "$oldsecrets" | while IFS= read -r line ; do echo "$line"; sed -i -e "s/$line/JWT_SECRET=$secret/g" "$env"; done; fi
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement