PHP Example Laravel authentication principle and full custom authentication

Source: Internet
Author: User
Tags php example
Recently in the study Laravel framework, so the following article mainly to you about the Laravel authentication principle and fully customized certification of the relevant information, the text through the sample code introduced in very detailed, the need for friends can reference, the following with small series to learn together

Objective

Laravel The default Auth functionality is already comprehensive, but we often encounter some situations that require customization, such as validating fields and default mismatches, such as the need to be able to satisfy both user name and email authentication, and so on. How do I create a fully customizable certification? Compared to a tutorial, I prefer to introduce how it works, so that it is more handy in the process of self-modification or customization.

Authenticatable interface

Illuminate\contracts\auth\authenticatable

Authenticatable defines an interface that can be used to authenticate a model or class that needs to be implemented, that is, if a custom class is required for authentication, the method that defines the interface needs to be implemented.

Gets the name of the field uniquely identified, which can be used for authentication, such as Id,uuidpublic function Getauthidentifiername ();//Gets the value corresponding to the identifier public function Getauthidentifier ();//Obtain the Authentication password public function Getauthpassword ();//Get Remember Tokenpublic function Getremembertoken () ;//Set Remember Tokenpublic function Setremembertoken ($value);//Get the field name of the remember token, such as the default ' Remember_token ' Public fu Nction Getremembertokenname ();

For example, your authentication model needs to use ' token ' instead of ' password ' as the password verification, this time you can modify the return value of the Getauthpassword () method as ' token ';

Authenticatable Trait

Illuminate\auth\authenticatable

Authenticatable trait, defined in Laravel, is also the auth of Laravel trait Default user model, which defines the user model default authentication identifier as ' ID ' and the Password field ' trait ' , the remember token corresponds to the field remember_token and so on.

You can modify some settings by overriding these methods of the User model.

Guard interface

Illuminate\contracts\auth\guard

The Guard interface defines an authentication method that implements the Authenticatable (certified) model or class, as well as some common interfaces.

Determines whether the current user is logged on to public function check ();//Determines whether the current user is a visitor (not logged in) Public function guest ();//Gets the currently authenticated user public function user ();// Gets the ID of the currently authenticated user, which is strictly not necessarily the ID, should be the only field name defined in the previous model public function ID ();//Authentication user Public function validate (array $ Credentials = []);//Set Current user public function SetUser (authenticatable $user);

Statefulguard interface

Illuminate\contracts\auth\statefulguard

The Statefulguard interface inherits from the guard interface and adds a further, stateful guard in addition to some of the basic interfaces defined in the guard.

The newly added interfaces have these:

Attempts to verify that the user is legitimate public function attempt (array $credentials = [], $remember = False) based on the credentials provided;//log in once, do not log session or Cookiepubli C function once (array $credentials = []);//login user, usually record session and cookie Public function login (authenticatable $user, after successful verification, $remember = False);//Login to Public function Loginusingid ($id, $remember = False) using the user ID;//login with user ID, but do not log session and Cookiep ublic function Onceusingid ($id);//automatically log in to Public function Viaremember () by remember token in the cookie;//Sign out public Function logo UT ();

The Laravel is provided by default in the 3 Guard:requestguard,tokenguard,sessionguard.

Requestguard

Illuminate\auth\requestguard

Requestguard is a very simple guard. The Requestguard is certified by passing in a closure package. You can add a custom requestguard by calling Auth::viarequest.

Sessionguard

Illuminate\auth\sessionguard

Sessionguard is the default guard for Laravel Web authentication.

Tokenguard

Illuminate\auth\tokenguard

Tokenguard is available for stateless API authentication through token authentication.

Userprovider interface

Illuminate\contracts\auth\userprovider

The Userprovider interface defines a method for obtaining an authentication model, such as acquiring a model based on an ID, obtaining a model from an email, and so on.

Obtain the authentication model by a unique identifier public function Retrievebyid ($identifier);//Get model Public function by unique identifier and remember token Retrievebytoken ($identifier, $token);//Update remember Tokenpublic function Updateremembertoken with a given authentication model ( Authenticatable $user, $token);//The Public Function retrievebycredentials (array $credentials) to obtain a user, such as an email or user name, from a given credential. ;//Authentication whether the given user and the given voucher conform to public function validatecredentials (authenticatable $user, array $credentials);

The default in Laravel is two user Provider:databaseuserprovider & Eloquentuserprovider.

Databaseuserprovider

Illuminate\auth\databaseuserprovider

Obtain the authentication model directly from the database table.

Eloquentuserprovider

Illuminate\auth\eloquentuserprovider

Obtaining the authentication model through the eloquent model

AuthManager

Illuminate\auth\authmanager

Guard is used to authenticate the success of a user, Userprovider is used to provide the source of the authentication model, and according to the project's Config Management guard and custom guard and so on, it is implemented through AuthManager.

AuthManager should be a bit like the Context class in the strategy mode and factory method inside the factory, on the one hand to manage Guard, on the other hand through the __call Magic method invoke the specific strategy (Guard) method.

Auth facade corresponds to the implementation class is authmanager,authmanager registered in the container as a singleton, to manage all the guard, user provider and guard agent work.

Custom Certifications

Based on the above knowledge, it is easy to know that you want to customize a certification.

    • Create an authentication model

Create a custom authentication model to implement the Authenticatable interface;

    • Create a custom Userprovider

Create a custom Userprovider, implement the Userprovider interface, can return the above custom authentication model;

    • Create a custom Guard

Create a custom guard to implement the guard or Statefulguard interface

    • Add guard creator and user provider creator to AuthManager

Add the following code to the boot method of the Appserviceprovider:

Auth::extend (' Myguard ', function () {... return new myguard ();//Return Custom Guard instance ...}); Auth::p rovider (' Myuserprovider ', function () {return new Myuserprovider ();//Return custom user provider});

Add a custom guard to the guards array in config\auth.php, a custom guard consisting of two parts: Driver and provider.

' Oustn ' = [' Driver ' = ' myguard ', ' provider ' = ' myusers ',],

Add a custom user provider to the providers array in config\auth.php.

' Myusers ' = [' Driver ' = ' myuserprovider '//inside the specific fields can be added according to the information you need to create user provider, you can Auth::createuserprovider (' Myuserprovider ') created],

Set the Defaults.guard for config\auth.php to OUSTN.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.