Detailed description of the Auth module in Laravel and laravelauth
Preface
This article mainly introduces the Auth module in Laravel and shares it for your reference. I will not talk much about it below. Let's take a look at the detailed introduction.
This article analyzes and writes the code of the localization module based on Laravel 5.4;
Module composition
The Auth module is divided into two parts: user authentication and permission management. In terms of file composition, the Illuminate \ Auth \ Passwords directory contains a small module for Password Reset or forgot password processing, illuminate \ Auth is the module responsible for user authentication and permission management. Illuminate \ Foundation \ Auth provides specific logic implementation in a system column such as logon, password change, and password reset;
Describes and briefly describes the relationship between each file in the Auth module;
User Authentication
HTTP itself is stateless. In the process of system interaction, the account or Token ID is used to determine the authenticated user;
Configuration File explanation
return [ 'defaults' => [ 'guard' => 'web', ... ], 'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'token', 'provider' => 'users', ], ], 'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => App\User::class, ], ],], ];
From bottom up, understanding;
- Providers is an interface that provides User data. To mark the driver object and target object, the key name users is the name of a set of providers, which is driven by eloquent and modal is App \ User: class;
- The guards part is configured for the authentication management part. There are two authentication methods: web and api. web authentication is based on Session interaction and user IDs are obtained based on sessionId, this user is queried in the users provider. api authentication is based on token value interaction, and the users provider is also used;
- Defaults indicates that web authentication is used by default;
Authentication
Session binding authentication information:
// $ Credentials array stores authentication conditions, such as email address or user name, password // $ remember indicates whether to remember, generate 'Remember _ token' public function attempt (array $ credentials = [], $ remember = false) public function login (AuthenticatableContract $ user, $ remember = false) public function loginUsingId ($ id, $ remember = false)
HTTP Basic Authentication. authentication information is placed in the request header. The subsequent requests are accessed by sessionId;
public function basic($field = 'email', $extraConditions = [])
Only authenticate in the current session. authentication information is not recorded in the session:
public function once(array $credentials = [])public function onceUsingId($id)public function onceBasic($field = 'email', $extraConditions = [])
During authentication (including registration and password forgetting), the following events are defined:
| Event name |
Description |
| Attempting |
Verify the event |
| Authenticated |
Verification event |
| Failed |
Verification failure event |
| Lockout |
The number of failed attempts exceeds the limit. The attempt to access the request again is locked. |
| Logi |
Events called when a user successfully logs on using 'Remember _ token' |
| Logout |
User exit event |
| Registered |
User Registration event |
There are also some other authentication methods:
- Check whether Authenticated Users exist:
Auth::check()
- Obtain the current authenticated user:
Auth::user()
- Exit the system:
Auth::logout()
Password Processing
Configuration explanation
return [ 'defaults' => [ 'passwords' => 'users', ... ], 'passwords' => [ 'users' => [ 'provider' => 'users', 'table' => 'password_resets', 'expire' => 60, ], ],]
View the configuration from the bottom up;
- The passwords array indicates the password resetting configuration; the users is the alias of the configuration scheme, which contains three elements: provider (the solution provided by the user is the providers array above), table (table that stores the token used to reset the password), expire (token expiration time)
- The default option sets the default passwords Reset Scheme;
Call and implementation of Password Reset
First, let's see how Laravel's password reset function is implemented:
Public function reset (array $ credentials, Closure $ callback) {// verify whether the user name, password, and token are valid $ user = $ this-> validateReset ($ credentials); if (! $ User instanceof CanResetPasswordContract) {return $ user;} $ password = $ credentials ['Password']; // run the callback function to change the password and save $ callback ($ user, $ password); // delete the token saved by persistent storage when the password is reset $ this-> tokens-> delete ($ user); return static: PASSWORD_RESET ;}
Let's take a look at how the Reset Password module encapsulated by the Foundation \ Auth module is called:
// The exposed reset password APIpublic function reset (Request $ request) {// verify the request parameter token, email, password, password_confirmation $ this-> validate ($ Request, $ this-> rules (), $ this-> validationErrorMessages (); // call the password reset method. The second parameter is the callback, perform some persistent storage work $ response = $ this-> broker ()-> reset ($ this-> credentials ($ request), function ($ user, $ password) {$ this-> resetPassword ($ user, $ password) ;}); // encapsulate Response return $ response = Passwo Rd: PASSWORD_RESET? $ This-> sendResetResponse ($ response): $ this-> sendResetFailedResponse ($ request, $ response );} // obtain the Request parameter protected function credentials (request $ request) {return $ Request-> only ('email ', 'Password', 'password _ confirmation ', 'Token');} // After the password is verified for authenticity, the persistence work protected function resetPassword ($ user, $ password) {// The modified password, regenerate the remember_token $ user-> forceFill (['Password' => bcrypt ($ password), 'Remember _ token' => Str :: random (60),])-> save (); // The user information in the session is also assigned a new value $ this-> guard ()-> login ($ user );}
The general process of "forgot password => send email => Reset Password" is as follows:
- Click "forgot password" and go to the "forgot password" page through route configuration. The "email to be sent" field is required;
- Verify that the "email address to be sent" exists in the Database. If yes, a password reset email is sent to the email address;
- There is a link in the password reset email (the token will be taken to the password modification page after clicking it), and the database will save the hash encrypted value of the token;
- Fill in the "email", "password", and "Confirm Password" fields, and carry the token to access the Reset Password API. The homepage determines the mailbox, password, and password, verify that the token is valid. If yes, the token is successfully reset;
Permission management
Permission management is maintained by an array variable abilities maintained by the memory space. The structure is as follows:
$ Abilities = array ('defined action name, for example, use the as name of the route (common. dashboard. list) '=> function ($ user) {// the parameter of the method. The first parameter is $ user. The current user, and the following parameter can return true; // if true is returned, it indicates that you have the permission. If false is returned, you do not have the permission },......);
However, with only $ abilities, it is too annoying to use the defined part of the Code together, so there is a policy class;
The policy class defines the ing relationship between a group of entities and object permission classes. For example, in the document:
There is a Modal object class called Post, which can define a PostPolicy permission class for this object class, in which some actions are defined as method names;
Class PostPolicy {// update permission. Only the author of this article can modify public function update (User $ user, Post $ post) {return $ user-> id ===$ post-> user_id ;}}
Then register in ServiceProvider, so that the system will know that if the class you want to check is a Post object and you add the action name to it, the system will find the corresponding method of the PostPolicy class;
protected $policies = [ Post::class => PostPolicy::class,];
How to call it?
For permissions defined in the abilities array:
- Whether the current user has the common. dashboard. list permission: Gate: allows ('common. dashboard. list ')
- Whether the current user has the common. dashboard. list permission :! Gate: denies ('common. dashboard. list ')
- Whether the current user has the common. dashboard. list permission: $ request-> user ()-> can ('common. dashboard. list ')
- Whether the current user has the common. dashboard. list permission :! $ Request-> user ()-> cannot ('common. dashboard. list ')
- Whether the user has the common. dashboard. list permission: Gate: forUser ($ user)-> allows ('common. dashboard. list ')
Permission for policy and policy calls:
- Can the current user modify the article (called by Gate): Gate: allows ('update', $ post)
- Can the current user modify the article (called by the user): $ user-> can ('update', $ post)
- Whether the current user can modify the article (using the help function): policy ($ post)-> update ($ user, $ post)
- Can the current user modify the article (called in the Controller class method): $ this-> authorize ('update', $ post );
- Can the current user modify the article (called in the Controller class same name method): $ this-> authorize ($ post );
- Specify whether the user can modify the article (called in the Controller class method): $ this-> authorizeForUser ($ user, 'update', $ post );
Useful Techniques
Obtain the permissions registered by the current system, including two abilities and policies arrays. The Code is as follows:
$ Gate = app (\ Illuminate \ Contracts \ Auth \ Access \ Gate: class); $ reflection_gate = new ReflectionClass ($ gate ); $ policies = $ reflection_gate-> getProperty ('category'); $ policies-> setAccessible (true ); // obtain the currently registered arrays dump ($ policies-> getValue ($ gate); $ abilities = $ reflection_gate-> getProperty ('abilities '); $ abilities-> setAccessible (true); // obtain the currently registered abilities array dump ($ abilities-> getValue ($ gate ));
Summary
The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.