Laravel Password Management MechanismSeptember 22, 2016
Recently while working on one of my projects, I have been wondering how laravel password management mechanism works. I decided to take a deep dive into laravel core files to explore its functionality. So, in this article, we're going to do learn about laravel password mechanism step by step.
As we all know, laravel uses
bcrypt() function to generate passwords with the length of 60 characters.
bcrypt() is actually, a simple function that has been registered in laravel helpers file located under the Illuminate/Foundation folder.
If you can see, it uses hash key registered in laravel's core application.
In your HashServiceProvider.php file located under Illuminate/Hashing folder, you can see laravel registering hash key with the new instance of BcryptHasher class.
BcryptHasher is a simple php class that utilize's the php inbuilt password_hash functionality to generate unique passwords on every refresh. For example,
bcrypt('password') will generate different passwords on every refresh.
Since laravel generates different passwords on every refresh, we are going to see its password matching mechanism when you users try to log in.
Whenever user tries to attempt login, laravel calls attempt function in SessionGuard.php under Illuminate/Auth folder
Now, in order to get user details, laravel calls
retrieveByCredentials() function in either DatabaseUserProvider.php or EloquentUserProvider.php based on your configuration in config/auth.php. Here lets assume, you have given ‘eloquent' as your user service provider in auth configuration.
In the above code, you can clearly see that except password field laravel is taking every other file and applying it in where condition to get the user.
Once, the query ran successfully and it retrieves a user, laravel will call
hasValidCredentials() function in SessionGuard.php by passing the user data and credentials given during login attempt. This function will in return call
validCredentials() function in EloquentUserProvider.php file by passing the same parameters.
Inside validCredentials file, it calls the
check() function which is located in BcryptHasher file passing the plain password given by the user during login attempt and the user password registered in the database.
Finally, laravel utilize's php password_verify functionality to match the plain password and the encrypted password that is stored in the database table. If they match, then laravel will create user session, if not it will redirect back the user to login page.
Thats it! This is how laravel password mechanism works. Happy Coding!