Detailed auth modules in the Laravel framework

Source: Internet
Author: User
Recently encountered in the work of the Auth module, but the Auth module smattering, through the search for relevant information to learn, so the following this article mainly to you about the Auth module in laravel related information, the text through the sample code introduced in very detailed, the need for friends can reference, Let's take a look below.

Objective

This article is mainly about the Laravel in the Auth module of the relevant content, shared out for everyone to reference the study, the following words do not say, come together to see the detailed introduction bar.

This article is based on the Laravel 5.4 version of the localization module code for analysis and writing;

Module composition

Auth module is divided into two parts: User authentication and Rights management, from the file composition, Illuminate\auth\passwords directory is the password reset or forget the password processing of the small module, Illuminate\auth is responsible for user authentication and Rights Management module, Illuminate\foundation\auth provides a system-specific logical implementation such as login, password change, password reset and so on.

The relationship between the files of Auth module is presented, and a brief description is made.

User authentication

HTTP itself is stateless, usually in the process of system interaction, using the account or token identification to determine the authentication user;

Configuration file Interpretation

return [' defaults ' + = [' Guard ' + ' web ', ...], ' guards ' + [  ' web ' = = ['  driver ' = ' session ', 
   ' provider ' + ' users ',], ' API ' = [   ' driver ' = ' token ',   ' provider ' + ' users ',], ' providers ' = = [' Users ' = [  ' driver ' = ' eloquent ',  ' model ' = App\user::class,],],]  ;

From the bottom up, understand;

    • Providers is the interface to provide user data, to label the drive object and target object; Here, the key name users is a set of provider name, using eloquent driver, modal is app\user::class;

    • Guards part of the Authentication Management section for configuration, there are two authentication methods, one called the Web, there is a api;web authentication is based on session interaction, according to SessionID to obtain the user ID, the users this provider query out this user API authentication is based on token value interaction, also using users this provider;

    • The defaults item shows that the Web authentication is used by default;

Certification

Session Binding authentication Information:

$credentials array holds authentication conditions, such as mailbox or username, password//$remember indicates whether to remember, generate ' remember_token ' public function attempt (array $ Credentials = [], $remember = false) public  function login (authenticatablecontract $user, $remember = false) public Fu Nction Loginusingid ($id, $remember = False)

HTTP Basic Authentication, authentication information placed on the request header, and subsequent request access via SessionID;

Public Function Basic ($field = ' email ', $extraConditions = [])

Authentication is not recorded in the current session only, and no authentication information is logged in sessions:

Public function once (array $credentials = []) public function Onceusingid ($id) Public function oncebasic ($field = ' email ', $ Extraconditions = [])

During the authentication process (including registration, forgotten password), the defined events have these:

Event name Description
Attempting Attempt to validate event
Authenticated Verifying through events
Failed Validation Failure Events
Lockout The number of failures exceeds the limit and locks the request again to access the event
Logi Event called when successful login via ' Remember_token '
Logout User Exit Events
Registered User Registration Events

There are a few other authentication methods:

    • Check if there are authenticated users:Auth::check()

    • To obtain the current authenticated user:Auth::user()

    • Exit System:Auth::logout()

Password handling

Configuration interpretation

return [' defaults ' + = ['  passwords ' + ' users ',  ...],  ' passwords ' = ['  users '   and ' = ' PR Ovider ' + ' users ',   ' table ' = ' password_resets ',   ' expire ', ' = ',],]  

From the bottom up, look at the configuration;

    • The passwords array is the configuration of the reset password, and the users are the aliases for the configuration scheme, containing three elements: provider (the scheme that provides the user, which is the providers array above), table (which holds the tables that store the token of the password reset), Expire (token expiry time)

    • The default key sets the passwords reset scheme;

Reset Password Call and implementation

Let's see how the Laravel Reset Password function is implemented:

The Public function reset (array $credentials, Closure $callback) {//verifies that the user name, password, and token are valid $user = $this->validatereset ($CR Edentials); if (! $user instanceof canresetpasswordcontract) {   return $user;}   $password = $credentials [' Password ']; The callback function executes the change password, and persists the storage $callback ($user, $password); Save token $this->tokens->delete ($user) persisted when deleting reset password; return static::P Assword_reset;}

And look at how the Reset cipher module encapsulated by the Foundation\auth module is called:

Reset Password exposed apipublic function reset (Request $request) {//Verify request parameters token, email, password, password_confirmation $this Validate ($request, $this->rules (), $this->validationerrormessages ()); Call the Reset password method, the second parameter is the callback, do some persistent storage work $response = $this->broker ()->reset ($this->credentials ($request), function ($user, $password)  {$this->resetpassword ($user, $password); } ); Package Response return $response = = Password::P assword_reset? $this->sendresetresponse ($response): $this->sendresetfailedresponse ($request, $response);} Get request parameters for Reset password protected function credentials (request $request) {return $request->only (' email ', ' password ', ' Passwo Rd_confirmation ', ' token ');} After resetting the authenticity of the password, the persisted work Protected function ResetPassword ($user, $password) {//modified password, regenerate Remember_token $user Forcefill ([' Password ' = bcrypt ($password), ' remember_token ' = Str::random (),])->save (); The user information in the session is also re-assigned $this->guard ()->login ($user);}

The general flow of "forgot Password = email + reset Password" is as follows:

    • Click "Forgot Password", through the routing configuration, skip to the "Forgot password" page, the page has "to send the mailbox" this field to fill;

    • Verify that the mailbox to be sent is present in the database and, if present, sends a reset password message to the mailbox;

    • The Reset password message has a link (which will carry tokens to the Change Password page after the click), and the database will hold the token's hash encrypted value;

    • Fill in the "Mailbox", "Password", "Confirm Password" three fields, carry token access to reset Password API, the first page to determine the mailbox, password, Confirm password three fields, and then verify that token is valid, if yes, reset success;

Rights Management

Rights management is maintained by an array variable that relies on memory space maintenance, with the following structure: abilities

$abilities = Array (' defined action name, such as the as name of the route (common.dashboard.list) ' = = ' function ($user) {  //method parameter, first bit is $user, current user, The following parameters can be self-determined return  true;//return true means have permissions, false means no permissions}, ...);

But only with the $abilities, will use the definition of the part of the code together too annoying cable, so there is a policy strategy class appears;

The policy policies class defines a set of entity and entity permission classes that correspond to each other, for example by article:

There is a modal entity class called Post, you can define a Postpolicy permission class for this entity class, in which the permission class defines some actions as the method name;

Class Postpolicy {//update permission, the article author can modify the Public function update (User $user, Post $post) {  return $user->id = = = $po st->user_id; }}

Then register in ServiceProvider, so the system will know that if you want to check the class is a post object, plus you give the action name, the system can find the corresponding method of the Postpolicy class;


protected $policies = [Post::class = Postpolicy::class,];

How to invoke it?

For the permissions defined in the abilities array:

    • Whether the current user has Common.dashboard.list permissions: gate::allows (' common.dashboard.list ')

    • Whether the current user has Common.dashboard.list permissions:! Gate::d enies (' common.dashboard.list ')

    • Whether the current user has Common.dashboard.list permissions: $request->user ()->can (' Common.dashboard.list ')

    • Whether the current user has Common.dashboard.list permissions:! $request->user ()->cannot (' Common.dashboard.list ')

    • Specify whether the user has Common.dashboard.list permissions: Gate::foruser ($user)->allows (' Common.dashboard.list ')

Permissions for the policy policies class call:

    • Whether the current user can modify the article (Gate call): Gate::allows (' Update ', $post)

    • Whether the current user can modify the article (user call): $user->can (' Update ', $post)

    • Whether the current user can modify the article (with help function): Policy ($post)->update ($user, $post)

    • Whether the current user can modify the article (called in the Controller class method): $this->authorize (' Update ', $post);

    • Whether the current user can modify the article (called in a method with the same name as the Controller Class): $this->authorize ($post);

    • Specifies whether the user can modify the article (called in the Controller class method): $this->authorizeforuser ($user, ' Update ', $post);

Useful tips

Gets the permissions for the current system registration, including the two-part abilities and policies array contents, with the following code:

 $gate = App (\illuminate\contracts\auth\access\gate::class); $reflection _gate = new Reflectionclass ($gate); $policies = $reflection _gate->getproperty (' policies '); $policies->setaccessible (                          true);//Gets the currently registered policies array dump ($policies->getvalue ($gate));          $abilities = $reflection _gate->getproperty (' abilities '); $abilities->setaccessible (TRUE);//Gets the currently registered abilities array dump ($abilities->getvalue ($gate)); 
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.