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.phpshowLoginForm(); } /** * 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') {!! Form::open(['url'=>'auth/login']) !!} //這裡跟路由表配置要相匹配,post提交到auth/login {!! Form::label('email', 'Email:') !!} //登入項有2個,一個是email一個是password {!! Form::email('email', null, ['class' => 'form-control']) !!} {!! Form::label('password', 'Password:') !!} {!! Form::password('password', ['class' => 'form-control']) !!} {!! Form::submit('登入',['class'=>'btn btn-primary form-control']) !!} {!! Form::close() !!} //這個代碼是額外的,主要是為了看驗證失敗的時候的報錯資訊,laravel會將錯誤資訊寫到$errors裡面去,所以能夠在頁面擷取來看 @foreach($errors->all() as $error) - {{$error}}
@endforeach
@stop
然後我們配置註冊頁面
這裡我們有4個欄位,有3個事必須的,name,password,email,因為這個對應AuthController的create方法的值,其實這個也是跟model的表有關,因為我們的user表也就是使用這3個欄位來做驗證的。
resources/views/auth/register.blade.php@extends('layout.app')@section('content') {!! Form::open(['url'=>'auth/register']) !!} //注意這裡是post到auth/register {!! Form::label('name', 'Name:') !!} {!! Form::text('name', null, ['class' => 'form-control']) !!} {!! Form::label('email', 'Email:') !!} {!! Form::email('email', null, ['class' => 'form-control']) !!} {!! Form::label('password', 'Password:') !!} {!! Form::password('password', ['class' => 'form-control']) !!} {!! Form::label('password_confirmation', 'Password_confirmation:') !!} //需要注意的是,這個password_confirmation是有講究的,如果不是這樣寫的話,會導致validator驗證不通過 {!! Form::password('password_confirmation', ['class' => 'form-control']) !!} {!! Form::submit('註冊',['class'=>'btn btn-primary form-control']) !!} {!! Form::close() !!} @foreach($errors->all() as $error) - {{$error}}
@endforeach
@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就是校正這個東西的,判斷是否能登陸之類。