配置JWT认证获取Token失败,提示私钥文件不存在或不可读
Got it, let's tackle this JWT authentication error you're hitting. The error message is pretty clear—your app can't find or access the private key file at /var/www/config/jwt/private.pem. Here's how to fix it step by step:
1. Verify the private key exists
First, check if the key files are actually in the specified directory. SSH into your server and run:
ls -la /var/www/config/jwt/
If you don't see private.pem and public.pem listed, you need to generate them first.
2. Generate the JWT key pair
Use the Lexik bundle's built-in command to create the keys. Make sure you're in your project root directory when running this:
php bin/console lexik:jwt:generate-keypair
By default, this puts the keys in config/jwt/. If you need them in /var/www/config/jwt/ specifically, use the --path flag:
php bin/console lexik:jwt:generate-keypair --path=/var/www/config/jwt
You might be prompted for a passphrase—remember it, you'll need it in your config if you set one.
3. Fix file permissions
Even if the files exist, your web server user (usually www-data on Apache/Nginx) might not have permission to read them. Run these commands to set the right permissions:
# Set ownership to the web server user chown www-data:www-data /var/www/config/jwt/private.pem /var/www/config/jwt/public.pem # Restrict private key access (only owner can write, group can read) chmod 640 /var/www/config/jwt/private.pem # Make public key readable by everyone chmod 644 /var/www/config/jwt/public.pem
4. Double-check your Lexik JWT config
Open your config/packages/lexik_jwt_authentication.yaml file and confirm the paths match where your keys are stored. It should look something like this:
lexik_jwt_authentication: secret_key: '%env(resolve:JWT_SECRET_KEY)%' # This should point to /var/www/config/jwt/private.pem public_key: '%env(resolve:JWT_PUBLIC_KEY)%' # This should point to /var/www/config/jwt/public.pem pass_phrase: '%env(JWT_PASSPHRASE)%' # If you set a passphrase during key generation, add it here
Also, check your .env file to ensure JWT_SECRET_KEY and JWT_PUBLIC_KEY are set correctly:
JWT_SECRET_KEY=/var/www/config/jwt/private.pem JWT_PUBLIC_KEY=/var/www/config/jwt/public.pem JWT_PASSPHRASE=your_passphrase_here # If applicable
After going through these steps, try your curl command again. That should resolve the 500 error and let you get a valid JWT token.
内容的提问来源于stack exchange,提问作者Romain LANCIA

