f7n
f7n

Reputation: 1684

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.

Upvotes: 15

Views: 53346

Answers (3)

Ayman Elshehawy
Ayman Elshehawy

Reputation: 2954

Just run this command:

php artisan jwt:secret

Reference

Upvotes: 25

Tekgno
Tekgno

Reputation: 76

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

Upvotes: 2

Loek
Loek

Reputation: 4135

From the documentation:

Don't forget to set a secret key in the config file!

Since you can't find the key in a search, I think you haven't actually published the config:

php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\JWTAuthServiceProvider"

The docs seem pretty clear and the issues on GitHub don't mention the problems you're having, so take a peek into them and see if you maybe skipped step. Happens to the best of us! https://github.com/tymondesigns/jwt-auth/wiki/Installation

Upvotes: 1

Related Questions