Laravel Authentication Principle and Completely Custom Authentication Detailed Explanation

  • 2021-10-25 06:07:25
  • OfStack

Preface

The default auth function of Laravel is already very comprehensive, but we often encounter some situations that need to be customized, such as the mismatch between the verified fields and the default, such as the need to meet user, name and email authentication at the same time, and so on. How to create a fully customized authentication? Compared with a tutorial, I prefer to introduce the working principle of 1, so that I can modify or customize myself more conveniently.

Authenticatable interface

Illuminate\Contracts\Auth\Authenticatable

Authenticatable defines the interface that a model or class that can be used for authentication needs to implement, that is, if a custom class needs to be used for authentication, the method defined by this interface needs to be implemented.


//  Get only 1 Identified field name that can be used for authentication, such as  id , uuid
public function getAuthIdentifierName();
//  Gets the value corresponding to the identifier 
public function getAuthIdentifier();
//  Get the password for authentication 
public function getAuthPassword();
//  Get remember token
public function getRememberToken();
//  Settings  remember token
public function setRememberToken($value);
//  Get  remember token  The corresponding field name, such as the default  'remember_token'
public function getRememberTokenName();

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

Authenticatable trait

Illuminate\Auth\Authenticatable

Authenticatable trait defined in Laravel is also trait used by the default User model of Laravel auth. This trait defines that the default authentication identifier of User model is' id ', the password field is' password ', and the corresponding field of remember token is remember_token, etc.

Some settings can be modified by overriding these methods of User model.

Guard interface

Illuminate\Contracts\Auth\Guard

The Guard interface defines an authentication method that implements an Authenticatable (authenticatable) model or class and some common interfaces.


//  Judge whether the current user logs in or not 
public function check();
//  Judge whether the current user is a tourist (not logged in) 
public function guest();
//  Get the currently authenticated user 
public function user();
//  Object of the current authenticated user  id Strictly speaking, no 1 It must be  id That should be the only one defined in the previous model 1 Field name of 
public function id();
//  Authenticate the user according to the provided message 
public function validate(array $credentials = []);
//  Set the current user 
public function setUser(Authenticatable $user);

StatefulGuard interface

Illuminate\Contracts\Auth\StatefulGuard

The StatefulGuard interface inherits from the Guard interface. In addition to the basic interfaces defined in Guard, the stateful Guard is added.

The newly added interfaces are as follows:


//  Try to verify that the user is legal based on the credentials provided 
public function attempt(array $credentials = [], $remember = false);
// 1 Secondary login, no record session or cookie
public function once(array $credentials = []);
//  Login user, usually recorded after successful authentication  session  And  cookie 
public function login(Authenticatable $user, $remember = false);
//  User  id  Login 
public function loginUsingId($id, $remember = false);
//  User  ID  Log in, but do not record  session  And  cookie
public function onceUsingId($id);
//  Pass  cookie  In  remember token  Automatic login 
public function viaRemember();
//  Logout 
public function logout();

guard of 3 is provided by default in Laravel: RequestGuard, TokenGuard and SessionGuard.

RequestGuard

Illuminate\Auth\RequestGuard

RequestGuard is a very simple guard. RequestGuard is authenticated by passing in a closure. You can add a custom RequestGuard by calling Auth:: viaRequest.

SessionGuard

Illuminate\Auth\SessionGuard

SessionGuard is the default guard for Laravel web certification.

TokenGuard

Illuminate\Auth\TokenGuard

TokenGuard is suitable for stateless api authentication and has passed token authentication.

UserProvider interface

Illuminate\Contracts\Auth\UserProvider

The UserProvider interface defines methods for obtaining authentication models, such as obtaining models from id, obtaining models from email, and so on.


//  Through only 1 Identifier Acquisition Authentication Model 
public function retrieveById($identifier);
//  Through only 1 Identifiers and  remember token  Get the model 
public function retrieveByToken($identifier, $token);
//  Update with a given authentication model  remember token
public function updateRememberToken(Authenticatable $user, $token);
//  Get the user through a given credential, such as  email  Or user name and so on 
public function retrieveByCredentials(array $credentials);
//  Verify that the given user and the given credentials match 
public function validateCredentials(Authenticatable $user, array $credentials);

There are two user provider: DatabaseUserProvider by default in Laravel & EloquentUserProvider.

DatabaseUserProvider

Illuminate\Auth\DatabaseUserProvider

The authentication model is obtained directly through the database table.

EloquentUserProvider

Illuminate\Auth\EloquentUserProvider

Obtain authentication model through eloquent model

AuthManager

Illuminate\Auth\AuthManager

Guard is used to authenticate whether a user is authenticated successfully, UserProvider is used to provide the source of authentication model, and the functions of managing guard and customizing guard according to config of the project are realized through AuthManager.

AuthManager should be a bit like Context class in policy mode and factory in factory method. One aspect manages Guard, and the other aspect calls specific policy (Guard) method through __call magic method.

The corresponding implementation classes of Auth and facade are AuthManager and AuthManager registered as singletons in the container, which are used to manage all the proxy work of guard, user, provider and guard.

Custom authentication

According to the above knowledge, you can know that it is very simple to customize 1 authentication.

Creating an Authentication Model

Create a custom authentication model to realize Authenticatable interface;

Create a custom UserProvider

Create a custom UserProvider and realize UserProvider interface, which can return the authentication model customized above;

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 AppServiceProvider:


Auth::extend('myguard', function(){
 ...
 return new MyGuard(); // Return to Custom  guard  Instances 
 ...
});

Auth::provider('myuserprovider', function(){
 return new MyUserProvider(); //  Returns a custom  user provider
});

Add a custom guard to the guards array of config\ auth. php. One custom guard consists of two parts: driver and provider.


'oustn' => [
 'driver' => 'myguard',
 'provider' => 'myusers',
],

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


'myusers' => [
 'driver' => 'myuserprovider' //  The specific fields inside can be created according to you  user provider  The required information can be added freely through  Auth::createUserProvider('myuserprovider')  Create 
],

Set defaults. guard for config\ auth. php to oustn.

Summarize


Related articles: