In Laravel when you try to run php artisan, you may sometimes encounter the error: Unable to read key from file file:///var/www/mysite/storage/oauth-private.key at vendor/league/oauth2-server/src/CryptKey.php:64.

This error occurs when Laravel cannot find or access the private key file (oauth-private.key) used for the OAuth2 authentication. To resolve this issue, follow the steps provided in this post.

Fixing: oauth-private.key does not exist or is not readable

To solve this issue, follow these steps:

  1. Verify the existence of the key files

Make sure the oauth-private.key and oauth-public.key files exist in the storage directory of your Laravel project, usually located at storage/app. If these files do not exist, you will need to generate them.

  1. Generate the key files

If the key files are missing, you can generate them using the following Artisan command:

php artisan passport:install

This command will generate the oauth-private.key and oauth-public.key files and place them in the storage directory.

If you have already installed Laravel Passport and just need to regenerate the keys, you can use the following command:

php artisan passport:keys --force

This command will force the generation of new oauth-private.key and oauth-public.key files, overwriting any existing keys.

  1. Set the correct permissions

Ensure that the key files have the correct permissions so that your web server can read them. You can use the chmod command to set the permissions:

chmod 600 storage/oauth-private.key
chmod 600 storage/oauth-public.key

This will set the read and write permissions for the owner of the files only.

  1. Create symbolic links

This step is needed if you are running Laravel on a shared hosting environment, you may need to create symbolic links to the key files. Run the following commands:

ln -s /path/to/your/laravel/storage/app/oauth-private.key oauth-private.key
ln -s /path/to/your/laravel/storage/app/oauth-public.key oauth-public.key

Make sure to replace /path/to/your/laravel with the actual path to your Laravel project.

  1. Update the .env file

Make sure the APP_URL and APP_STORAGE variables in your .env file have the correct values:

APP_URL=http://yourdomain.com
APP_STORAGE=storage/app

Replace http://yourdomain.com with your actual domain.

This is not an essential step to follow to solve the problem, but it’s a good practice when using Laravel to build your projects.

  1. Clear the config cache

Run the following command to clear the configuration cache:

php artisan config:clear

By following these steps, you should resolve the “oauth-private.key does not exist or is not readable” error in your Laravel project.

Final considerations

After following these steps, the error should be resolved. If you still encounter issues, double-check the file paths, permissions, and .env variables, and make sure your Laravel Passport package is correctly installed and up-to-date.