search
HomeBackend DevelopmentPHP TutorialAnalysis of Laravel5 quick authentication logic flow

This article mainly introduces the analysis of Laravel5's fast authentication logic process. It has certain reference value. Now I share it with you. Friends in need can refer to it.

Laravel5 itself comes with a set of user authentication function, just use the command line php artisan make:auth and php artisan migrate under the new project to use the built-in fast authentication function.

The following is a logical analysis of the login function, which is based on Laravel 5.5 version.

Get the login route (red box) through the command php artisan route:list:

Open and view /app/Http/Controller/Auth/LoginController.php , the file code is very concise. In fact, the login logic and methods are integrated in the trait of Illuminate/Foundation/Auth/AuthenticatesUsers:

##View the Illuminate\Foundation\Auth\AuthenticatesUsers code The login method, the parameter $request is the request object, which contains the login request information including login name, password, etc.:

line31: The validateLogin method is responsible for calling The validate method of the controller itself verifies whether the username and password comply with simple rules. There is no need to go into this in depth.

It is worth noting the username method marked in the red box. Developers can customize this method in LoginController to override the trait method and customize the login account field. The trait defaults to ' email'.

Do not directly change the username() method of the trait and maintain the integrity of the Laravel5 framework. The reason will not be explained in detail.

line36: hasTooManyLoginAttempts method, used to check whether the number of account login attempts reaches the set maximum value.

This method refers to the trait of Illuminate\Foundation\Auth\ThrottlesLogins. Looking at the trait name, you can guess that it is responsible for avoiding violent logins.

Limiter() in the above figure returns a RateLimiter object (as the name implies: frequency limiter), which is created by the app service container. This object originates from: Illuminate\Cache\RateLimiter file.

As can be seen from the location of this object, it uses the Laravel caching mechanism to handle the number of logins.

So the hasTooManyLoginAttempts method in the above picture calls the tooManyAttempts method of the RateLimiter object to verify the number of logins:

the tooManyAttempt method has three parameters:

$key: The corresponding key used by cacche to save the login number of the current account. The key composition is like this:

So the key value is roughly like this: "email|101:10:45:12". It can be seen from here that the brute force cracking prevention uses IP. Of course, if I change my IP, I can still try to log in again. Although there are always limitations, it is still much better than being naked.

$maxAttempts: Setting value for the maximum number of login attempts.

This value can be customized. You can write the custom maxAttempts attribute in LoginController. The default is 5 times:

$decayMinutes:The waiting time (minutes) for resuming login after reaching the maximum number of attempts.

This value is also customizable. Customize this property in LoginController. The default is 1 minute:

Go back to the RateLimiter::tooManyAttempts method. This method It will determine whether the current number of logins has reached the set value. If it reaches the set value and is still within the last prohibited login time range, it will return true, indicating that the current user (IP) is still prohibited from logging in.

The red box in the picture below is used to determine whether the $key.':timer' value exists in the cache. This value uses the $decayMinutes time above as the expiration time, so the existence of this value is Key to restore login status.

If the cache value does not exist, the current user can log in. At this time, the resetAttempts method clears the value of $key cached login times and starts recording from zero.

The code execution right returns to line 36 of Illuminate\Foundation\Auth\AuthenticatesUsers again:

When hasTooManyLoginAttempts returns true, the Lockout event is initiated and the LockoutResponse response is returned. Users can generate a Lockout event monitor to process the logic related to the event, such as recording login logs, etc.

LockoutResponse response essentially throws a verification exception, which will be automatically interpreted by Laravel as a response with a 423 status code and accompanied by auth.throttle configuration information. The original language of this configuration is located at: /resources/lang/en/auth.php. Users can customize their own language information.

Then, return to line 42 of Illuminate\Foundation\Auth\AuthenticatesUsers and start to perform login verification:

attemptLogin method passes config/auth.php Configure the guard name, generate the corresponding guard object, and then call the object's attempt for login verification.

Laravel5 guard currently supports two types: SessionGuard and tokenGuard, both are saved in the Illuminate\Auth folder, and they are both implemented in the Illuminate\Contracts\Auth\Guard interface. So if you need to customize the watcher, please implement this interface.
If you want to implement a web guard, you can further implement the Illuminate\Contracts\Auth\StatefulGuard interface.

As for which guard to use under which circumstances, they are all configured in config/auth.php:

Since what I analyzed this time is Web login process, so check the attempt method of Illuminate\Auth\sessionGuard:

#line 351: The function of this line is to retrieve the account information through the configured provider provider. There are also two types of providers: DatabaseUserProvider and EloquentUserProvider. The file is located at: /Illuminate/Auth.

The specific provider to use is configured through the providers parameter of config/auth.php. After configuration, you also need to specify which provider to use in the 'guards' parameter. The provider essentially provides a way to query the database account table. Database directly uses the database Db facade to query, while eloquent uses a model to query.

Laravel uses EloquentUserProvider by default. Looking at the retrieveByCredentials method, it is obvious that the user information is retrieved directly by the account name:

Back The attempt method of Illuminate\Auth\sessionGuard and the hasValidCredentials method of line 356 verify the password, if the user information in the previous step can be retrieved normally.

As can be seen from the hasValidCredentials method body, it calls the provider's validateCredentials method for password verification. Check out the EloquentUserProvider::validateCredentials method:

This verification method uses the check method of the hash class implemented by the HasherContract contract. The specific implementation classes are: Illuminate\Hashing\BcryptHasher. Let's look at the check method of this class:

Obviously, it uses the password_verify function to compare the entered plaintext password with the hashed password value. This requires that the database passwords have been hashed using password_hash.

If the password verification is successful, return true. Return to sessionGuard and execute the login method of line357 to record the session and cookie login status.

The key and value of the saved session are:

'key'=>'login_session_'.sha1(static::class) // static::class refers to the sessionGuard class itself

'value'=>The primary key value of the current user

If the remember_me option is used, the following cookie is saved, and the key and value are as follows:

'key'=>''remember_session_'.sha1(static::class) //static::class refers to the sessionGuard class itself

'value'=>User primary key value .'|'.The latest remembered_token value saved.'|'.User password hash value

At this point, the user has successfully logged in, and the execution point finally returns to line 42 of Illuminate\Foundation\Auth\AuthenticatesUsers , attemptLogin has been executed and returned true, and then the sendLoginResponse method is called to jump to the main page after login or the last login page.

Note that the authenticated method is an empty method. You can redefine this method in LoginController to customize how to jump and process other logic after login.

If the login is unsuccessful, execute the incrementLoginAttempts($request) method of Illuminate\Foundation\Auth\AuthenticatesUsers to increase the number of failed logins. The method to increase the number of times is also to indirectly call the hit() method of the RateLimiter class.
Finally call sendFailedLoginResponse to return a login exception.

Finally, the timing diagram is attached. The drawing is average. Some UML concepts are not well grasped. Sorry:

That’s all. The entire content of this article is hoped to be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

Introduction to Laravel’s Eloquent model

How to use Wamp to build a Php local development environment and HBuilder debugging

The above is the detailed content of Analysis of Laravel5 quick authentication logic flow. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain how load balancing affects session management and how to address it.Explain how load balancing affects session management and how to address it.Apr 29, 2025 am 12:42 AM

Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

Explain the concept of session locking.Explain the concept of session locking.Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Are there any alternatives to PHP sessions?Are there any alternatives to PHP sessions?Apr 29, 2025 am 12:36 AM

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Define the term 'session hijacking' in the context of PHP.Define the term 'session hijacking' in the context of PHP.Apr 29, 2025 am 12:33 AM

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.

What is the full form of PHP?What is the full form of PHP?Apr 28, 2025 pm 04:58 PM

The article discusses PHP, detailing its full form, main uses in web development, comparison with Python and Java, and its ease of learning for beginners.

How does PHP handle form data?How does PHP handle form data?Apr 28, 2025 pm 04:57 PM

PHP handles form data using $\_POST and $\_GET superglobals, with security ensured through validation, sanitization, and secure database interactions.

What is the difference between PHP and ASP.NET?What is the difference between PHP and ASP.NET?Apr 28, 2025 pm 04:56 PM

The article compares PHP and ASP.NET, focusing on their suitability for large-scale web applications, performance differences, and security features. Both are viable for large projects, but PHP is open-source and platform-independent, while ASP.NET,

Is PHP a case-sensitive language?Is PHP a case-sensitive language?Apr 28, 2025 pm 04:55 PM

PHP's case sensitivity varies: functions are insensitive, while variables and classes are sensitive. Best practices include consistent naming and using case-insensitive functions for comparisons.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)