目錄
这是我理解的过程图
首先看AuthController
然后我们看AuthenticatesAndRegistersUsers
然后我们再看AuthenticatesUsers
然后我们再看RegistersUsers.php
然后我们配置登录页面
然后我们配置注册页面
然后我们看AuthenticatesUsers.php
然后我们再看AuthController.php
首頁 後端開發 php教程 laravel 5.2 用户注册和登录

laravel 5.2 用户注册和登录

Jun 20, 2016 pm 12:27 PM

laravel5.2 验证有所改动,增加了一个叫guard的东西,这个东西主要是负责检查用户的session之类的

原文有提到: https://laravel.com/docs/5.2/authentication#introduction

At its core, Laravel’s authentication facilities are made up of “guards” and “providers”. Guards define how users are authenticated for each request. For example, Laravel ships with a session guard which maintains state using session storage and cookies and a token guard, which authenticates users using a “API token” that is passed with each request.

这个命令会自动创建一些验证相关的文件resources/views/auth 和resources/views/layouts,不过我们暂时先不用,先理解过程。

php artisan make:auth
登入後複製

先提前布置一下路由表

app/Http/routes.phpRoute::group(['middleware' => ['web']], function () {    Route::resource('/articles','ArticlesController');    Route::get('auth/login','Auth\AuthController@getLogin'); //打开登录页面,用get    Route::post('auth/login','Auth\AuthController@postLogin'); //提交request给login页面的postLogin方法,其实是给Auth\AuthController的postLogin    Route::get('auth/register','Auth\AuthController@getRegister'); //类似    Route::post('auth/register','Auth\AuthController@postRegister');//类似    Route::get('auth/logout','Auth\AuthController@getLogout'); //logout单独独立出来,也是类似的方式使用//        Route::get('auth/logout',function(){//            Auth::logout();//        });});
登入後複製

需要说明一下:

1. 上面这些在laravel 5.2里面都是要包含在web这个中间件的[‘middleware’ => [‘web’],除了csrf之外,还有一些验证的逻辑会有关联。

2. login 和 register是在“保护”内的,而logout则不是,具体可以看AuthController.php,主要是因为logout比较随意,也不能用session来限制其访问

3. 上面这些路由都不是默认提供的,需要自己手写,主要是因为laravel 5.2开始没有提供,不过正因为这样,整个流程也比较清晰的整理出来

4. laravel这个默认登录注册是需要跟model关联的,如果model有问题,则也会影响整个过程,laravel把很多东西都封装好了,对于一般人来说,不容易知道里面的流程怎么生效的,需要不断研究学习源码才行。

这是我理解的过程图

首先看AuthController

app/Http/Controllers/Auth/AuthController.php< ?phpnamespace App\Http\Controllers\Auth;use App\User;use Validator;use App\Http\Controllers\Controller;use Illuminate\Foundation\Auth\ThrottlesLogins;use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;class AuthController extends Controller{    /*    |--------------------------------------------------------------------------    | Registration & Login Controller    |--------------------------------------------------------------------------    |    | This controller handles the registration of new users, as well as the    | authentication of existing users. By default, this controller uses    | a simple trait to add these behaviors. Why don't you explore it?    |    */    use AuthenticatesAndRegistersUsers, ThrottlesLogins;  //使用了这2个类作为主要的验证功能类,下面会说到    /**     * Where to redirect users after login / registration.     *     * @var string     */    protected $redirectTo = '/';  //这个是登录成功的重定向链接,有时候需要修改。    /**     * Create a new authentication controller instance.     *     * @return void     */    public function __construct()    {        $this->middleware($this->guestMiddleware(), ['except' => 'logout']);   //排除了logout,不在中间件保护范围内    }    /**     * Get a validator for an incoming registration request.     *     * @param  array  $data     * @return \Illuminate\Contracts\Validation\Validator     */    protected function validator(array $data)  //这里自带了一个验证逻辑,request的验证有2种方法,一种是写request文件,一种就是用validator    {        return Validator::make($data, [            'name' => 'required|max:255',            'email' => 'required|email|max:255|unique:users',            'password' => 'required|min:6|confirmed',  //默认有这些验证逻辑,这个逻辑是有讲究的,因为默认的laravel验证注册登录是会关联到这里的。        ]);    }    /**     * Create a new user instance after a valid registration.     *     * @param  array  $data     * @return User     */    protected function create(array $data)  //这个就是create,在函数体里面就是用了model的create方法,直接在数据库生成数据    {        return User::create([            'name' => $data['name'],            'email' => $data['email'],            'password' => bcrypt($data['password']),        ]);    }}
登入後複製

然后我们看AuthenticatesAndRegistersUsers

vendor/laravel/framework/src/Illuminate/Foundation/Auth/AuthenticatesAndRegistersUsers.php< ?phpnamespace Illuminate\Foundation\Auth;trait AuthenticatesAndRegistersUsers{    use AuthenticatesUsers, RegistersUsers {//这里是重点,使用了两个类,一个是验证用户,一个是注册用户        AuthenticatesUsers::redirectPath insteadof RegistersUsers;          AuthenticatesUsers::getGuard insteadof RegistersUsers;    }}
登入後複製

然后我们再看AuthenticatesUsers

因为我们在路由上写了要调用getlogin,postlogin,getregister,postregister,而AuthenticatesUsers就是主要处理getlogin,postlogin的。

vendor/laravel/framework/src/Illuminate/Foundation/Auth/AuthenticatesUsers.php<?phpnamespace Illuminate\Foundation\Auth;use Illuminate\Http\Request;use Illuminate\Support\Facades\Auth;use Illuminate\Support\Facades\Lang;trait AuthenticatesUsers{    use RedirectsUsers;    /**     * Show the application login form.     *     * @return \Illuminate\Http\Response     */    public function getLogin()  //getLogin在此!    {        return $this->showLoginForm();    }    /**     * Show the application login form.     *     * @return \Illuminate\Http\Response     */    public function showLoginForm()  //其实调用这个showLoginForm    {        $view = property_exists($this, 'loginView')                    ? $this->loginView : 'auth.authenticate';        if (view()->exists($view)) {            return view($view);        }        return view('auth.login'); //看到这里可以看出,判断是否存在auth.authenticate文件,如果没有则用auth.login,这个文件其实就是views文件夹下面的blade文件,即resources/views/auth/login.blade.php    }    /**     * Handle a login request to the application.     *     * @param  \Illuminate\Http\Request  $request     * @return \Illuminate\Http\Response     */    public function postLogin(Request $request) //这里是postlogin    {        return $this->login($request);    }    /**     * Handle a login request to the application.     *     * @param  \Illuminate\Http\Request  $request     * @return \Illuminate\Http\Response     */    public function login(Request $request) //其实调用的是login    {        $this->validateLogin($request);        // If the class is using the ThrottlesLogins trait, we can automatically throttle        // the login attempts for this application. We'll key this by the username and        // the IP address of the client making these requests into this application.        $throttles = $this->isUsingThrottlesLoginsTrait();  //这个是判读用户登录的频率相关的        if ($throttles && $lockedOut = $this->hasTooManyLoginAttempts($request)) {  //这里有一个更详细的toomanylogin            $this->fireLockoutEvent($request);            return $this->sendLockoutResponse($request);        }        $credentials = $this->getCredentials($request);  //这里是用来确认用户是否登陆过,会跟remember有关,就是免登陆相关的。        if (Auth::guard($this->getGuard())->attempt($credentials, $request->has('remember'))) {            return $this->handleUserWasAuthenticated($request, $throttles);        }        // If the login attempt was unsuccessful we will increment the number of attempts        // to login and redirect the user back to the login form. Of course, when this        // user surpasses their maximum number of attempts they will get locked out.        if ($throttles && ! $lockedOut) {            $this->incrementLoginAttempts($request);        }        return $this->sendFailedLoginResponse($request);    }    /**     * Validate the user login request.     *     * @param  \Illuminate\Http\Request  $request     * @return void     */    protected function validateLogin(Request $request)    {        $this->validate($request, [            $this->loginUsername() => 'required', 'password' => 'required',        ]);    }    /**     * Send the response after the user was authenticated.     *     * @param  \Illuminate\Http\Request  $request     * @param  bool  $throttles     * @return \Illuminate\Http\Response     */    protected function handleUserWasAuthenticated(Request $request, $throttles)    {        if ($throttles) {            $this->clearLoginAttempts($request);        }        if (method_exists($this, 'authenticated')) {            return $this->authenticated($request, Auth::guard($this->getGuard())->user());        }        return redirect()->intended($this->redirectPath());    }    /**     * Get the failed login response instance.     *     * @param \Illuminate\Http\Request  $request     * @return \Illuminate\Http\Response     */    protected function sendFailedLoginResponse(Request $request)    {        return redirect()->back()            ->withInput($request->only($this->loginUsername(), 'remember'))            ->withErrors([                $this->loginUsername() => $this->getFailedLoginMessage(),            ]);    }    /**     * Get the failed login message.     *     * @return string     */    protected function getFailedLoginMessage()    {        return Lang::has('auth.failed')                ? Lang::get('auth.failed')                : 'These credentials do not match our records.';    }    /**     * Get the needed authorization credentials from the request.     *     * @param  \Illuminate\Http\Request  $request     * @return array     */    protected function getCredentials(Request $request)    {        return $request->only($this->loginUsername(), 'password');    }    /**     * Log the user out of the application.     *     * @return \Illuminate\Http\Response     */    public function getLogout()    {        return $this->logout();    }    /**     * Log the user out of the application.     *     * @return \Illuminate\Http\Response     */    public function logout()    {        Auth::guard($this->getGuard())->logout();        return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/');    }    /**     * Get the guest middleware for the application.     */    public function guestMiddleware()    {        $guard = $this->getGuard();        return $guard ? 'guest:'.$guard : 'guest';    }    /**     * Get the login username to be used by the controller.     *     * @return string     */    public function loginUsername()    {        return property_exists($this, 'username') ? $this->username : 'email';    }    /**     * Determine if the class is using the ThrottlesLogins trait.     *     * @return bool     */    protected function isUsingThrottlesLoginsTrait()    {        return in_array(            ThrottlesLogins::class, class_uses_recursive(static::class)        );    }    /**     * Get the guard to be used during authentication.     *     * @return string|null     */    protected function getGuard()    {        return property_exists($this, 'guard') ? $this->guard : null;    }}
登入後複製

然后我们再看RegistersUsers.php

这个主要处理getregister,postregister

vendor/laravel/framework/src/Illuminate/Foundation/Auth/RegistersUsers.php< ?phpnamespace Illuminate\Foundation\Auth;use Illuminate\Http\Request;use Illuminate\Support\Facades\Auth;trait RegistersUsers{    use RedirectsUsers;    /**     * Show the application registration form.     *     * @return \Illuminate\Http\Response     */    public function getRegister() //这里就是getRegister    {        return $this->showRegistrationForm();    }    /**     * Show the application registration form.     *     * @return \Illuminate\Http\Response     */    public function showRegistrationForm()  //其实调用的是他    {        if (property_exists($this, 'registerView')) {            return view($this->registerView);        }        return view('auth.register');  //看逻辑可以知道,如果没有registerView的话就用auth.register来作为注册页,原理跟login差不多    }    /**     * Handle a registration request for the application.     *     * @param  \Illuminate\Http\Request  $request     * @return \Illuminate\Http\Response     */    public function postRegister(Request $request) //这里是postRegister    {        return $this->register($request);    }    /**     * Handle a registration request for the application.     *     * @param  \Illuminate\Http\Request  $request     * @return \Illuminate\Http\Response     */    public function register(Request $request)  //其实是用他,这里有点复杂    {        $validator = $this->validator($request->all());          if ($validator->fails()) {  //会先去判断是否能够通过validator,而这个validator就是之前在AuthController.php的那个,而且这个throwValidationException(并不是在页面的显示错误的                                    //是在这里storage/logs/laravel.log            $this->throwValidationException(                $request, $validator            );        }        Auth::guard($this->getGuard())->login($this->create($request->all()));         //这里通过调用getGuard来判断是否确认写入数据库,这里首先通过create写入数据库,然后进行login登录,登录成功了,就是下面的回调页面了。好巧妙。        return redirect($this->redirectPath()); //注册成功返回的那个回调页面,也是在AuthController.php配    }    /**     * Get the guard to be used during registration.     *     * @return string|null     */    protected function getGuard()    {        return property_exists($this, 'guard') ? $this->guard : null;  //这个就是判断auth.php里的guard的。    }}
登入後複製

然后我们配置登录页面

resources/views/auth/login.blade.php@extends('layout.app')@section('content')    <div class="col-md-4 col-md-offset-4">        {!! Form::open(['url'=>'auth/login']) !!}  //这里跟路由表配置要相匹配,post提交到auth/login                <!--- Email Field --->        <div class="form-group">            {!! Form::label('email', 'Email:') !!}     //登录项有2个,一个是email一个是password            {!! Form::email('email', null, ['class' => 'form-control']) !!}        </div>        <!--- Password Field --->        <div class="form-group">            {!! Form::label('password', 'Password:') !!}            {!! Form::password('password', ['class' => 'form-control']) !!}        </div>        {!! Form::submit('登录',['class'=>'btn btn-primary form-control']) !!}        {!! Form::close() !!}    </div>    <ul class="list-group">   //这个代码是额外的,主要是为了看验证失败的时候的报错信息,laravel会将错误信息写到$errors里面去,所以能够在页面获取来看        @foreach($errors->all() as $error)            <li class="list-group-item list-group-item-danger">{{$error}}</li>        @endforeach    </ul>@stop
登入後複製

然后我们配置注册页面

这里我们有4个字段,有3个事必须的,name,password,email,因为这个对应AuthController的create方法的值,其实这个也是跟model的表有关,因为我们的user表也就是使用这3个字段来做验证的。

resources/views/auth/register.blade.php@extends('layout.app')@section('content')    <div class="col-md-4 col-md-offset-4">        {!! Form::open(['url'=>'auth/register']) !!}  //注意这里是post到auth/register                <!--- Name Field --->        <div class="form-group">            {!! Form::label('name', 'Name:') !!}                {!! Form::text('name', null, ['class' => 'form-control']) !!}        </div>        <!--- Email Field --->        <div class="form-group">            {!! Form::label('email', 'Email:') !!}            {!! Form::email('email', null, ['class' => 'form-control']) !!}        </div>        <!--- Password Field --->        <div class="form-group">            {!! Form::label('password', 'Password:') !!}            {!! Form::password('password', ['class' => 'form-control']) !!}        </div>       <!--- Password-confirm Field --->        <div class="form-group">            {!! Form::label('password_confirmation', 'Password_confirmation:') !!}  //需要注意的是,这个password_confirmation是有讲究的,如果不是这样写的话,会导致validator验证不通过            {!! Form::password('password_confirmation', ['class' => 'form-control']) !!}        </div>        {!! Form::submit('注册',['class'=>'btn btn-primary form-control']) !!}        {!! Form::close() !!}    </div>        <ul class="list-group">        @foreach($errors->all() as $error)            <li class="list-group-item list-group-item-danger">{{$error}}</li>        @endforeach    </ul>@stop
登入後複製

然后我们看AuthenticatesUsers.php

vendor/laravel/framework/src/Illuminate/Foundation/Auth/AuthenticatesUsers.php    public function getLogout()   //这里就是getLogout    {        return $this->logout();    }    /**     * Log the user out of the application.     *     * @return \Illuminate\Http\Response     */    public function logout()  //其实是他    {        Auth::guard($this->getGuard())->logout();        return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/auth/login');          //这里需要注意的是,这里logout的重定向地址需要设置一下,默认是/但是如果/是要登录才可以看的话,那么就会出错。    }
登入後複製

然后我们再看AuthController.php

app/Http/Controllers/Auth/AuthController.php    protected $redirectTo = '/articles'; //刚才我们提到登录成功的重定向地址就是这个$redirectTo    protected $guard = 'web';  //这个guard是特别的,是因为laravel5.2的关系
登入後複製

对此官网的解释

Guard CustomizationYou may also customize the "guard" that is used to authenticate users. To get started, define a guard property on your AuthController. The value of this property should correspond with one of the guards configured in your auth.php configuration file:protected $guard = 'admin';
登入後複製

你要设置一个guard的值,并且要跟auth.php对应好,然后我们再看看auth.php

config/auth.php< ?phpreturn [    /*    |--------------------------------------------------------------------------    | Authentication Defaults    |--------------------------------------------------------------------------    |    | This option controls the default authentication "guard" and password    | reset options for your application. You may change these defaults    | as required, but they're a perfect start for most applications.    |    */    'defaults' => [        'guard' => 'web',  //默认指定了一个guard 是叫web的        'passwords' => 'users',    ],    /*    |--------------------------------------------------------------------------    | Authentication Guards    |--------------------------------------------------------------------------    |    | Next, you may define every authentication guard for your application.    | Of course, a great default configuration has been defined for you    | here which uses session storage and the Eloquent user provider.    |    | All authentication drivers have a user provider. This defines how the    | users are actually retrieved out of your database or other storage    | mechanisms used by this application to persist your user's data.    |    | Supported: "session", "token"    |    */    'guards' => [        'web' => [  //然后这个叫web的guard呢有driver和provider这些属性,一个是session 驱动,一个是users的provider,简单理解就是用users表和session来做guard,这个guard可以理解为校验            'driver' => 'session',            'provider' => 'users',        ],        'api' => [            'driver' => 'token',            'provider' => 'users',        ],    ],    /*    |--------------------------------------------------------------------------    | User Providers    |--------------------------------------------------------------------------    |    | All authentication drivers have a user provider. This defines how the    | users are actually retrieved out of your database or other storage    | mechanisms used by this application to persist your user's data.    |    | If you have multiple user tables or models you may configure multiple    | sources which represent each model / table. These sources may then    | be assigned to any extra authentication guards you have defined.    |    | Supported: "database", "eloquent"    |    */    'providers' => [        'users' => [  //这里再次解释了users的这个provider就是一个eloquent,就是model Users            'driver' => 'eloquent',            'model' => App\User::class,        ],        // 'users' => [        //     'driver' => 'database',        //     'table' => 'users',        // ],    ],];
登入後複製

注册成功后会有数据在数据库生成检查数据库

id  name    email   password    remember_token  created_at  updated_at1   123456  1239@qq.com $2y$10$EfEo1gCcK6JdwgxjqjNbK.fVZjgu7i68uKMPqNwBX9VpNVuvgthm6    wSaR4V256k4xxisbbiVNS1o9iEqwCaIDZB5Nk5YZYj5JNBENIiowTALrBNNT    2016-05-25 15:31:07 2016-05-25 15:41:53
登入後複製

每次登录成功都会有一个laravel_session,而guard就是校验这个东西的,判断是否能登陆之类。

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1664
14
CakePHP 教程
1422
52
Laravel 教程
1316
25
PHP教程
1267
29
C# 教程
1239
24
PHP和Python:比較兩種流行的編程語言 PHP和Python:比較兩種流行的編程語言 Apr 14, 2025 am 12:13 AM

PHP和Python各有優勢,選擇依據項目需求。 1.PHP適合web開發,尤其快速開發和維護網站。 2.Python適用於數據科學、機器學習和人工智能,語法簡潔,適合初學者。

說明PHP中的安全密碼散列(例如,password_hash,password_verify)。為什麼不使用MD5或SHA1? 說明PHP中的安全密碼散列(例如,password_hash,password_verify)。為什麼不使用MD5或SHA1? Apr 17, 2025 am 12:06 AM

在PHP中,應使用password_hash和password_verify函數實現安全的密碼哈希處理,不應使用MD5或SHA1。1)password_hash生成包含鹽值的哈希,增強安全性。 2)password_verify驗證密碼,通過比較哈希值確保安全。 3)MD5和SHA1易受攻擊且缺乏鹽值,不適合現代密碼安全。

PHP行動:現實世界中的示例和應用程序 PHP行動:現實世界中的示例和應用程序 Apr 14, 2025 am 12:19 AM

PHP在電子商務、內容管理系統和API開發中廣泛應用。 1)電子商務:用於購物車功能和支付處理。 2)內容管理系統:用於動態內容生成和用戶管理。 3)API開發:用於RESTfulAPI開發和API安全性。通過性能優化和最佳實踐,PHP應用的效率和可維護性得以提升。

PHP:網絡開發的關鍵語言 PHP:網絡開發的關鍵語言 Apr 13, 2025 am 12:08 AM

PHP是一種廣泛應用於服務器端的腳本語言,特別適合web開發。 1.PHP可以嵌入HTML,處理HTTP請求和響應,支持多種數據庫。 2.PHP用於生成動態網頁內容,處理表單數據,訪問數據庫等,具有強大的社區支持和開源資源。 3.PHP是解釋型語言,執行過程包括詞法分析、語法分析、編譯和執行。 4.PHP可以與MySQL結合用於用戶註冊系統等高級應用。 5.調試PHP時,可使用error_reporting()和var_dump()等函數。 6.優化PHP代碼可通過緩存機制、優化數據庫查詢和使用內置函數。 7

什麼是HTTP請求方法(獲取,發布,放置,刪除等),何時應該使用? 什麼是HTTP請求方法(獲取,發布,放置,刪除等),何時應該使用? Apr 09, 2025 am 12:09 AM

HTTP請求方法包括GET、POST、PUT和DELETE,分別用於獲取、提交、更新和刪除資源。 1.GET方法用於獲取資源,適用於讀取操作。 2.POST方法用於提交數據,常用於創建新資源。 3.PUT方法用於更新資源,適用於完整更新。 4.DELETE方法用於刪除資源,適用於刪除操作。

解釋self ::,parent ::和static :: in php oop中的區別。 解釋self ::,parent ::和static :: in php oop中的區別。 Apr 09, 2025 am 12:04 AM

在PHPOOP中,self::引用當前類,parent::引用父類,static::用於晚靜態綁定。 1.self::用於靜態方法和常量調用,但不支持晚靜態綁定。 2.parent::用於子類調用父類方法,無法訪問私有方法。 3.static::支持晚靜態綁定,適用於繼承和多態,但可能影響代碼可讀性。

PHP如何安全地上載文件? PHP如何安全地上載文件? Apr 10, 2025 am 09:37 AM

PHP通過$\_FILES變量處理文件上傳,確保安全性的方法包括:1.檢查上傳錯誤,2.驗證文件類型和大小,3.防止文件覆蓋,4.移動文件到永久存儲位置。

PHP類型提示如何起作用,包括標量類型,返回類型,聯合類型和無效類型? PHP類型提示如何起作用,包括標量類型,返回類型,聯合類型和無效類型? Apr 17, 2025 am 12:25 AM

PHP類型提示提升代碼質量和可讀性。 1)標量類型提示:自PHP7.0起,允許在函數參數中指定基本數據類型,如int、float等。 2)返回類型提示:確保函數返回值類型的一致性。 3)聯合類型提示:自PHP8.0起,允許在函數參數或返回值中指定多個類型。 4)可空類型提示:允許包含null值,處理可能返回空值的函數。

See all articles