Home  >  Article  >  Backend Development  >  Laravel user authentication system (basic introduction)

Laravel user authentication system (basic introduction)

不言
不言Original
2018-07-06 14:18:413423browse

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();

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

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

, 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');
    }
}

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,
        ],
    ],

];

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);
}

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();
}

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 = []);
}

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);
}

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