A Simple Way to Protect Your Laravel Routes with Laravel Shield
The Laravel Shield package is a simple and lightweight package that adds HTTP Basic Authentication to Laravel routes. This can be useful for protecting sensitive routes and pages on your Laravel application from unauthorized access.
Installing Laravel Shield
To use Laravel Shield, you first need to install the package using Composer. Simply run the following command in your terminal:
composer require vinkla/laravel-shield
Protecting Routes with Laravel Shield
Once the package is installed, you can enable HTTP Basic Authentication for a route by adding the Shield middleware to the route. For example, the following code will protect the /admin route with HTTP Basic Authentication:
Route::get('/admin', 'AdminController@index')->middleware('shield');
When a user tries to access the protected route, they will be prompted to enter a username and password. The username and password will be checked against the credentials defined in your .env file.
Generating Password Hashes for Laravel Shield
To generate password hashes for use with Laravel Shield, you can use the bcrypt
function in combination with the artisan tinker
command. To do this, run the following command in your terminal:
php artisan tinker
This will open the tinker console, where you can use the bcrypt function to generate password hashes for the username and password. For example, to generate a password hash for the username admin and password password, you can use the following code:
bcrypt('admin')
bcrypt('password')
The bcrypt function will return a password hash for each of the username and password. You can then use these password hashes in your .env file. For example, you can update the SHIELD_USERNAME and SHIELD_PASSWORD values in your .env file to use the generated password hashes:
SHIELD_USERNAME=$2y$10$gwZG0VZ1e8hDp5R1Rdz5Ie7Yi5zFb6a3Uo3OeZ7vU6a1lFQb9q3Oa
SHIELD_PASSWORD=$2y$10$lkXcX3.0E72Tq3GJ/T0RRuZR/RZpI1ZsNtZ9XNcIYdYcJlzL8bwWW
If the user enters the correct username and password, they will be granted access to the protected route. If they enter the wrong credentials, they will be denied access and will be prompted to enter the correct credentials.
Conclusion
Overall, the Laravel Shield package is a simple and easy-to-use solution for adding HTTP Basic Authentication to your Laravel routes. It is a great way to protect sensitive routes on your application from unauthorized access without the need of a full authentication system.