Table of Contents
User authentication system (basic introduction)
Start using the Auth system
Guard
IlluminateContractsAuthGuard
IlluminateContractsAuthStatefulGuard
IlluminateContractsAuthSupportsBasicAuth
User Provider
User Provider Contract
Summary
Home Backend Development PHP Tutorial Laravel user authentication system (basic introduction)

Laravel user authentication system (basic introduction)

Jul 06, 2018 pm 02:18 PM
laravel php Source code analysis

This article mainly introduces the Laravel user authentication system (basic introduction), which has certain reference value. Now I share it with everyone. Friends in need can refer to

User authentication system (basic introduction)

Developers who have used Laravel know that Laravel comes with an authentication system to provide basic user registration, login, authentication, and password retrieval. If the basic functions provided by the Auth system do not meet the needs, it can still It is very convenient to expand on these basic functions. In this article, we first take a look at the core components of the Laravel Auth system.

The core of the Auth system is composed of the "guardian" and "provider" of Laravel's authentication component. The watcher defines how the user should be authenticated on each request. For example, Laravel's own session guard uses session storage and cookies to maintain state.

The following table lists the core components of the Laravel Auth system

Name Function
Auth Facade of AuthManager
AuthManager The external interface of the Auth authentication system, through which the authentication system provides The application provides all methods related to Auth user authentication, and the specific implementation details of the authentication methods are completed by the specific guard (Guard) it represents.
Guard Guard, defines how to authenticate users in each request
User Provider User provider, defines how to retrieve users from persistent storage data

In this article we will introduce these core components in detail, and then update the details of each component to the table given above at the end of the article.

Start using the Auth system

Just run the php artisan make:auth and php artisan migrate commands on your new Laravel application. The routes, views and data tables required by the Auth system are generated in the project.

php artisan make:authAfter execution, the view file required by the Auth authentication system will be generated. In addition, the response route will be added to the routing file web.php:

Auth::routes();
Copy after login

Auth The routes static method is defined separately in the Facade file

public static function routes()
{
    static::$app->make('router')->auth();
}
Copy after login

, so the specific routing methods of Auth are defined in Illuminate In the auth method of \Routing\Router, you can refer to the previous chapter on Facade source code analysis for how to find the actual class of the Facade class proxy.

namespace Illuminate\Routing;
class Router implements RegistrarContract, BindingRegistrar
{
    /**
     * Register the typical 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('register');
        $this->post('register', 'Auth\RegisterController@register');

        // Password Reset Routes...
        $this->get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->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');
    }
}
Copy after login

In the auth method, you can clearly see the routing URIs and corresponding controllers and methods of all functions provided in the authentication system.

Using Laravel's authentication system, almost everything is already configured for you. Its configuration file is located at config/auth.php, which contains clearly commented configuration options for adjusting the behavior of the authentication service.

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | 认证的默认配置
    |--------------------------------------------------------------------------
    |
    | 设置了认证用的默认"看守器"和密码重置的选项
    |
    */

    &#39;defaults&#39; => [
        &#39;guard&#39; => &#39;web&#39;,
        &#39;passwords&#39; => &#39;users&#39;,
    ],

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | 定义项目使用的认证看守器,默认的看守器使用session驱动和Eloquent User 用户数据提供者
    |
    | 所有的驱动都有一个用户提供者,它定义了如何从数据库或者应用使用的持久化用户数据的存储中取出用户信息
    |
    | Supported: "session", "token"
    |
    */

    &#39;guards&#39; => [
        &#39;web&#39; => [
            &#39;driver&#39; => &#39;session&#39;,
            &#39;provider&#39; => &#39;users&#39;,
        ],

        &#39;api&#39; => [
            &#39;driver&#39; => &#39;token&#39;,
            &#39;provider&#39; => &#39;users&#39;,
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | 所有的驱动都有一个用户提供者,它定义了如何从数据库或者应用使用的持久化用户数据的存储中取出用户信息
    |
    | Laravel支持通过不同的Guard来认证用户,这里可以定义Guard的用户数据提供者的细节:
    |        使用什么driver以及对应的Model或者table是什么
    |
    | Supported: "database", "eloquent"
    |
    */

    &#39;providers&#39; => [
        &#39;users&#39; => [
            &#39;driver&#39; => &#39;eloquent&#39;,
            &#39;model&#39; => App\Models\User::class,
        ],

        // &#39;users&#39; => [
        //     &#39;driver&#39; => &#39;database&#39;,
        //     &#39;table&#39; => &#39;users&#39;,
        // ],
    ],

    /*
    |--------------------------------------------------------------------------
    | 重置密码相关的配置
    |--------------------------------------------------------------------------
    |
    */

    &#39;passwords&#39; => [
        &#39;users&#39; => [
            &#39;provider&#39; => &#39;users&#39;,
            &#39;table&#39; => &#39;password_resets&#39;,
            &#39;expire&#39; => 60,
        ],
    ],

];
Copy after login

The core of the Auth system is composed of the "guardian" and "provider" of Laravel's authentication component. The watcher defines how the user should be authenticated on each request. For example, Laravel's built-in session watcher uses session storage and cookies to maintain state.

The provider defines how to retrieve users from persistent storage data. Laravel comes with support for retrieving users using Eloquent and the database query builder. 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 guard used in the configuration item is SessionGuard, and the user provider used is provided by EloquentProvider The model used by the server is App\User.

Guard

The guard defines how to authenticate the user on each request. The authentication system that comes with Laravel uses the built-in SessionGuard by default. SessionGuard In addition to implementing the methods in the \Illuminate\Contracts\Auth contract, it also implements Illuminate \Contracts\Auth\StatefulGuard and Illuminate\Contracts\Auth\SupportsBasicAuth methods in the contract. The methods defined in these Guard Contracts are the basic methods that the default authentication method of the Laravel Auth system relies on.

Let's first take a look at what operations these basic methods are intended to accomplish, and then we will get to know the specific implementation of these methods when we analyze how Laravel authenticates users through SessionGuard.

IlluminateContractsAuthGuard

This file defines the basic authentication method

namespace Illuminate\Contracts\Auth;

interface Guard
{
    /**
     * 返回当前用户是否时已通过认证,是返回true,否者返回false
     *
     * @return bool
     */
    public function check();

    /**
     * 验证是否时访客用户(非登录认证通过的用户)
     *
     * @return bool
     */
    public function guest();

    /**
     * 获取当前用户的用户信息数据,获取成功返回用户User模型实例(\App\User实现了Authenticatable接口)
     * 失败返回null
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function user();

    /**
     * 获取当前认证用户的用户ID,成功返回ID值,失败返回null
     *
     * @return int|null
     */
    public function id();

    /**
     * 通过credentials(一般是邮箱和密码)验证用户
     *
     * @param  array  $credentials
     * @return bool
     */
    public function validate(array $credentials = []);

    /**
     * 将一个\App\User实例设置成当前的认证用户
     *
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
     * @return void
     */
    public function setUser(Authenticatable $user);
}
Copy after login

IlluminateContractsAuthStatefulGuard

This Contracts defines the method used to authenticate users in the Laravel auth system. In addition to authenticating users, it also involves how to persist the user's authentication status after successful user authentication.

<?php

namespace Illuminate\Contracts\Auth;

interface StatefulGuard extends Guard
{
    /**
     * Attempt to authenticate a user using the given credentials.
     * 通过给定用户证书来尝试认证用户,如果remember为true则在一定时间内记住登录用户
     * 认证通过后会设置Session和Cookies数据
     * @param  array  $credentials
     * @param  bool   $remember
     * @return bool
     */
    public function attempt(array $credentials = [], $remember = false);

    /**
     * 认证用户,认证成功后不会设置session和cookies数据
     *
     * @param  array  $credentials
     * @return bool
     */
    public function once(array $credentials = []);

    /**
     * 登录用户(用户认证成功后设置相应的session和cookies)
     *
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
     * @param  bool  $remember
     * @return void
     */
    public function login(Authenticatable $user, $remember = false);

    /**
     * 通过给定的用户ID登录用户
     *
     * @param  mixed  $id
     * @param  bool   $remember
     * @return \Illuminate\Contracts\Auth\Authenticatable
     */
    public function loginUsingId($id, $remember = false);

    /**
     * 通过给定的用户ID登录用户并且不设置session和cookies
     *
     * @param  mixed  $id
     * @return bool
     */
    public function onceUsingId($id);

    /**
     * Determine if the user was authenticated via "remember me" cookie.
     * 判断用户是否时通过name为"remeber me"的cookie值认证的
     * @return bool
     */
    public function viaRemember();

    /**
     * 登出用户
     *
     * @return void
     */
    public function logout();
}
Copy after login

IlluminateContractsAuthSupportsBasicAuth

Defines the method of authenticating users through Http Basic Auth

namespace Illuminate\Contracts\Auth;

interface SupportsBasicAuth
{
    /**
     * 尝试通过HTTP Basic Auth来认证用户
     *
     * @param  string  $field
     * @param  array  $extraConditions
     * @return \Symfony\Component\HttpFoundation\Response|null
     */
    public function basic($field = &#39;email&#39;, $extraConditions = []);

    /**
     * 进行无状态的Http Basic Auth认证 (认证后不会设置session和cookies)
     *
     * @param  string  $field
     * @param  array  $extraConditions
     * @return \Symfony\Component\HttpFoundation\Response|null
     */
    public function onceBasic($field = &#39;email&#39;, $extraConditions = []);
}
Copy after login

User Provider

The user provider defines how to obtain persistence from To retrieve users from the stored data, Laravel defines a user provider contract (interface). All user providers must implement the abstract methods defined in this interface. Because a unified interface is implemented, whether it is Laravel's own or customized All user providers can be used by Guard.

User Provider Contract

The following are the abstract methods defined in the contract that must be implemented by the user provider:

<?php

namespace Illuminate\Contracts\Auth;

interface UserProvider
{
    /**
     * 通过用户唯一ID获取用户数据
     *
     * @param  mixed  $identifier
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function retrieveById($identifier);

    /**
     * Retrieve a user by their unique identifier and "remember me" token.
     * 通过Cookies中的"remeber me"令牌和用户唯一ID获取用户数据
     * @param  mixed   $identifier
     * @param  string  $token
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function retrieveByToken($identifier, $token);

    /**
     * 更新数据存储中给定用户的remeber me令牌
     *
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
     * @param  string  $token
     * @return void
     */
    public function updateRememberToken(Authenticatable $user, $token);

    /**
     * 通过用户证书获取用户信息
     *
     * @param  array  $credentials
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function retrieveByCredentials(array $credentials);

    /**
     * 验证用户的证书
     *
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
     * @param  array  $credentials
     * @return bool
     */
    public function validateCredentials(Authenticatable $user, array $credentials);
}
Copy after login

Through the configuration fileconfig/auth.php You can see that the default user provider used by Laravel is Illuminate\Auth\EloquentUserProvider. In the next chapter, when we analyze the implementation details of the Laravel Auth system, we will take a look at EloquentUserProvider How to implement the abstract methods in the user provider contract.

Summary

In this section we mainly introduce the basics of the Laravel Auth system, including the core components of the Auth system, the guardian and provider. The AuthManager completes user authentication by calling the guardian specified in the configuration file. , The user data required in the authentication process is obtained by the guard through the user provider. The following table summarizes the core components of the Auth system and the role of each component.

##AuthAuthManager’s FacadeAuthManagerThe external-facing interface of the Auth authentication system, through which the authentication system provides all Auth user authentication-related methods to the application, and the specific implementation details of the authentication methods are represented by it The specific guard (Guard) is used to complete. GuardGuard defines how to authenticate the user in each request. The user data required for authentication will be obtained through the user data provider. User ProviderThe user provider defines how to retrieve users from persistent storage data. When Guard authenticates users, it will obtain the user's data through the provider. All providers are implementations of the IlluminateContractsAuthUserProvider interface, providing specific implementation details for retrieving user data from persistent storage.
Name Function
#In the next chapter we will look at the implementation details of Laravel's own user authentication function.

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

Implementation details of Laravel user authentication system

Laravel WeChat applet obtains user details and brings them Analysis of parameter applet code expansion

The above is the detailed content of Laravel user authentication system (basic introduction). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP's Purpose: Building Dynamic Websites PHP's Purpose: Building Dynamic Websites Apr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

Why Use PHP? Advantages and Benefits Explained Why Use PHP? Advantages and Benefits Explained Apr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

PHP: Handling Databases and Server-Side Logic PHP: Handling Databases and Server-Side Logic Apr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

See all articles