This article mainly introduces about the Laravel user authentication system (basic introduction), has a certain reference value, now share to everyone, the need for friends can refer to
User authentication system (Basic introduction)
Developers who have used Laravel know that Laravel comes with a certification system to provide basic user registration, login, authentication, retrieve password, if the basic functions provided in the AUTH system do not meet the requirements can also be easily extended on these basic functions. In this article, let's take a look at the core components of the Laravel auth system.
The core of the Auth system consists of a "gatekeeper" and a "provider" of Laravel's certified components. The gatekeeper defines how each user in the request is authenticated. For example, Laravel's own session keeper uses session storage and cookies to maintain status.
The following table lists the core components of the Laravel auth system.
| name |
function |
| Auth |
AuthManager's facade |
| AuthManager |
Auth authentication system for external interface, authentication system through it to the application to provide all Auth user authentication-related methods, and the implementation details of the authentication method by its agent of the specific Guard (guard) to complete. |
| Guard |
A gatekeeper that defines how to authenticate the user in each request |
| User Provider |
User provider that defines how users are retrieved from persisted storage data |
In this article we will describe these core components in detail, and then update the details of each part's function to the table given above at the end of the article.
Getting started with the auth system
Simply run and command on the new Laravel php artisan make:auth application php artisan migrate to generate the routing and views and data tables required by the AUTH system in the project.
php artisan make:authAfter execution, the view file required by the Auth authentication system is generated, and the route of the response is increased in the routing file web.php :
Auth::routes ();
AuthThis static method is defined separately in the facade file. routes
public static function routes () { static:: $app->make (' router ')->auth ();}
So auth specific routing methods are defined in Illuminate\Routing\Router the auth method, about how to find the Facade class proxy real class can be looked up before facade source Analysis chapter.
Namespace Illuminate\routing;class Router implements Registrarcontract, bindingregistrar{/** * Register the Typica L Authentication routes for an application. * * @return void */Public Function auth () {//Authentication Routes ... $this->get (' login ' , ' Auth\logincontroller@showloginform ')->name (' login '); $this->post (' login ', ' auth\logincontroller@login '); $this->post (' logout ', ' auth\logincontroller@logout ')->name (' logout '); Registration Routes ... $this->get (' register ', ' Auth\registercontroller@showregistrationform ')->name (' Regi Ster '); $this->post (' register ', ' Auth\registercontroller@register '); Password Reset Routes ... $this->get (' Password/reset ', ' auth\forgotpasswordcontroller@showlinkrequestform ')-&G T;name (' password.request '); $this->post (' Password/email ', ' Auth\forgotpasswordcontroller@sendresetlinkemail ')->name (' Password.email ') ; $this->get(' Password/reset/{token} ', ' Auth\resetpasswordcontroller@showresetform ')->name (' Password.reset '); $this->post (' Password/reset ', ' auth\resetpasswordcontroller@reset '); }}
In the auth method, we can clearly see the route URI of all the functions provided in the authentication system and the corresponding controller and method.
With Laravel's authentication system, almost everything has been configured for you. Its configuration file is located config/auth.php , which contains a clear, annotated option configuration for adjusting the behavior of the authentication service.
<?phpreturn [/* |--------------------------------------------------------------------------| default configuration for authentication |--- ----------------------------------------------------------------------- | | Set the default "gatekeeper" and password reset options for authentication | */' defaults ' = [' guard ' = ' web ', ' passwords ' + ' users ',],/* |------------------- ------------------------------------------------------- | Authentication Guards |--------------------------------------------------------------------------| | Define the authentication keeper used by the project, the default keeper using session driver and eloquent user Data provider | | All drivers have a user provider that defines how user information is removed from the storage of persisted user data used by the database or application | | Supported: "Session", "token" | */' guards ' + [' web ' + = ' driver ' = ' session ', ' provider ' and ' users ', ], ' API ' = [' Driver ' = ' token ', ' provider ' + ' users ',],],/* |-------------------------------------------------------------------------- | User Providers |--------------------------------------------------------------------------| | All drivers have a user provider that defines how user information is removed from the storage of persisted user data used by the database or application | | Laravel supports authenticating users through different guard, where you can define the details of the user data provider for the guard: | What driver and the corresponding model or table is used | | Supported: "Database", "eloquent" | */' providers ' = [' users ' and ' = ' driver ' = ' eloquent ', ' model ' and ' = App\models \user::class,],//' users ' + = [//' driver ' + ' database ',//' table ' = = ' Us ERs ',//],],/* |--------------------------------------------------------------------------| Resetting password-related configurations |--------------------------------------------------------------------------| */' passwords ' + [' users ' and ' = ' provider ' + ' users ', ' table ' = ' password_r ' Esets ', ' expire ' = 60,],],;
The core of the Auth system consists of a "gatekeeper" and a "provider" of Laravel's certified components. The gatekeeper defines how each user in the request is authenticated. For example, Laravel's own session watchmen use session storage and cookies to maintain status.
The provider defines how the user is retrieved from the persisted storage data. The Laravel comes with support for retrieving users using the eloquent and database query constructors. Of course, you can customize other providers as needed.
So the above configuration file means that the Laravel authentication system uses the Web guard configuration item By default, the configuration item is using the gatekeeper is the Sessionguard, the user provider that is used by the EloquentProvider provider is the model that is used App\User .
Guard
The gatekeeper defines how each user in the request is authenticated. Laravel's own authentication system is used by default, in addition to implementing the methods in SessionGuard SessionGuard \Illuminate\Contracts\Auth the contract and the methods Illuminate\Contracts\Auth\StatefulGuard Illuminate\Contracts\Auth\SupportsBasicAuth in the contract, the methods defined in these guard contracts are laravel The AUTH system relies on the default authentication method.
Let's take a look at what these basic methods are intended to accomplish, and wait until the analysis Laravel is how the Sessionguard authenticates the user when it comes to the specific implementation of these methods.
Illuminatecontractsauthguard
This file defines the Basic authentication method
namespace Illuminate\contracts\auth;interface guard{ /** * Returns whether the current user has passed authentication, is true, returns false * * @ return BOOL * /Public function check (); /** * Verify if Guest user (user not logged in authentication) * * @return BOOL * /Public function Guest (); /** * Get the user information data for the current user, get the user model instance successfully returned (\app\user implements the Authenticatable interface) * failure returns null * @return \ Illuminate\contracts\auth\authenticatable|null * /Public function user (); /** * Gets the user ID of the current authenticated user, returns the ID value successfully, fails to return NULL * * @return Int|null * /public function ID (); /** * Authenticate users with credentials (typically mailbox and password) * * @param array $credentials * @return bool * /Public function validate (array $credentials = []); /** * Set a \app\user instance to the current authenticated user * * @param \illuminate\contracts\auth\authenticatable $ User * @return void * /Public Function SetUser (authenticatable $user);}
Illuminatecontractsauthstatefulguard
This contracts defines the method used when authenticating users in the Laravel auth system, in addition to authenticating users and how to persist the authentication status of the user after successful authentication.
<?phpnamespace illuminate\contracts\auth;interface Statefulguard extends guard{/** * Attempt to authenticate a User using the given credentials. * To try to authenticate the user by a given user certificate, if remember is true, the logged in user will be remembered for a certain period of time * the session and cookie data are set after authentication pass * @param array $credentials * @pa RAM BOOL $remember * @return BOOL */Public function attempt (array $credentials = [], $remember = false); /** * Authenticated Users, will not set session and cookie data after successful authentication * * @param array $credentials * @return bool */Public FU Nction once (array $credentials = []); /** * Login User (set the appropriate session and cookies after successful user authentication) * * @param \illuminate\contracts\auth\authenticatable $user * @p Aram BOOL $remember * @return void */Public Function login (authenticatable $user, $remember = false); /** * Login user with given user ID * * @param mixed $id * @param bool $remember * @return \illuminate\contracts\ auth\authenticatable */Public Function Loginusingid ($id, $remember = False); /** * Login user with given user ID and do not set session and cookies * @param mixed $id * @return BOOL */Public function on Ceusingid ($id); /** * Determine if the user was authenticated via "Remember Me" cookie. * @return BOOL */Public Function Viaremember () to determine if the user is authenticated with the cookie value of "Remeber me" by name; /** * Logout User * * @return void */Public function logout ();}
Illuminatecontractsauthsupportsbasicauth
Defines a method for authenticating users via HTTP Basic Auth
namespace Illuminate\contracts\auth;interface supportsbasicauth{ /** * Try to authenticate users with HTTP Basic Auth * * @param string $field * @param array $extraConditions * @return \symfony\component\ Httpfoundation\response|null * /Public Function Basic ($field = ' email ', $extraConditions = []); /** * Non-stateful HTTP Basic Auth authentication (session and cookies are not set after authentication) * * @param string $field * @ param Array $extraConditions * @return \symfony\component\httpfoundation\response|null */ Public function Oncebasic ($field = ' email ', $extraConditions = []);}
User Provider
The user provider defines how to retrieve the user from the persisted storage data, Laravel defines the user provider contract (interface), and all the user providers implement the abstract method defined in this interface, because the unified interface is implemented so that both the Laravel A custom user provider can be used by the guard.
User provider Contract
The following are the abstract methods defined in the contract that must be implemented by the user provider:
<?phpnamespace illuminate\contracts\auth;interface userprovider{/** * Get user data via user's unique ID * * @param mixed $identifier * @return \illuminate\contracts\auth\authenticatable|null */Public function Retrievebyid ($identif IER); /** * Retrieve a user by their unique identifier and "Remember Me" token. * Get user data via "Remeber Me" token and user unique ID in cookies * @param mixed $identifier * @param string $token * @return \ill Uminate\contracts\auth\authenticatable|null */Public Function Retrievebytoken ($identifier, $token); /** * Update the Remeber me token for a given user in the datastore * * @param \illuminate\contracts\auth\authenticatable $user * @param str ing $token * @return void */Public Function Updateremembertoken (authenticatable $user, $token); /** * Obtain user information via user certificate * * @param array $credentials * @return \illuminate\contracts\auth\authenticatable|nu ll */Public Function retrievebycredentials (array $credentials); /* * Verify User's certificate * * @param \illuminate\contracts\auth\authenticatable $user * @param array $credentials * @return BOOL */Public Function validatecredentials (authenticatable $user, array $credentials);}
With the configuration file config/auth.php you can see that the Laravel Default user provider is, in the Illuminate\Auth\EloquentUserProvider next section we analyze the details of Laravel auth system implementation, we'll look at EloquentUserProvider how to implement the abstract method in the user provider contract.
Summarize
In this section we mainly introduce the basis of the Laravel auth system, including the AUTH system's core component keeper and the provider, AuthManager through the invocation of the configuration file specified in the gatekeeper to complete the user authentication, the user data required in the authentication process is the gatekeeper through the user-provided device, The following table summarizes the core components of the AUTH system and the role of each component.
| name |
function |
| Auth |
AuthManager's facade |
| AuthManager |
Auth authentication system for external interface, authentication system through it to the application to provide all Auth user authentication-related methods, and the implementation details of the authentication method by its agent of the specific Guard (guard) to complete. |
| Guard |
A gatekeeper that defines how to authenticate the user in each request, and the user data that is required for authentication is obtained through the user data provider. |
| User Provider |
A user provider that defines how to retrieve a user from a persisted stored data, when the guard authenticates the user, takes the user's data through the provider, and all the providers are implementations of the Illuminatecontractsauthuserprovider interface. Provides specific implementation details for fetching user data from persistent storage. |
In the next section we will look at the implementation details of the user authentication feature that Laravel comes with.
The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!