laravel ÔõÑù¹Ø±ÕÓû§µÇ¼
laravel ÔõÑù¹Ø±ÕÓû§µÇ¼
ÔÚijЩÇéÐÎÏ£¬Äú¿ÉÄÜÐèÒª¹Ø±ÕÄúµÄ Laravel Ó¦ÓóÌÐòÖеÄÓû§µÇ¼¹¦Ð§£¬ÀýÈçÔÚά»¤Ê±´ú»òÔÚ¿ª·¢Ê±´ú¾ÙÐвâÊÔʱ¡£¹Ø±ÕÓû§µÇ¼²¢²»ÄÑ£¬Ö»Ðèƾ֤ÏÂÃæµÄ°ì·¨¾ÙÐвÙ×÷¼´¿É¡£
°ì·¨Ò»£º½ûÓ÷ÓÉ
Òª¹Ø±ÕÓû§µÇ¼£¬Ê×ÏÈÓ¦¸Ã½ûÓÃÓëÓû§µÇ¼Ïà¹ØµÄ·ÓÉ¡£ Laravel ĬÈÏÇéÐÎÏ»áΪÓû§Éí·ÝÑéÖ¤½¨ÉèÒÔÏ·ÓÉ£º
GET /login ÏÔʾµÇ¼±íµ¥
POST /login ´¦Öóͷ£µÇ¼±íµ¥Ìá½»
POST /logout ´¦Öóͷ£×¢ÏúÇëÇó
ÔÚÄúµÄÓ¦ÓóÌÐòÖУ¬¿ÉÄÜ»¹»áÓÐһЩÆäËûµÄÉí·ÝÑéÖ¤Ïà¹Ø·ÓÉ¡£ÈôÊÇÄúÏ뽫ÆäËùÓнûÓã¬ÇëÔÚÄúµÄ web ·ÓÉÎļþÖÐ×¢Ê͵ôËüÃÇ¡£
ʾÀý´úÂ룺
// ½ûÓÃÓû§µÇ¼·ÓÉ // Route::get('login', 'AuthLoginController@showLoginForm')->name('login'); // Route::post('login', 'AuthLoginController@login'); // Route::post('logout', 'AuthLoginController@logout')->name('logout');
µÇ¼ºó¸´ÖÆ
°ì·¨¶þ£º¹Ø±ÕÑéÖ¤ÖÐÐļþ
Laravel ÌṩÁËһϵÁÐÖÐÐļþÀ´´¦Öóͷ£Éí·ÝÑéÖ¤Ïà¹ØµÄ¹¦Ð§¡£ÆäÖУ¬Authenticate ÖÐÐļþÓÃÓÚÑéÖ¤Óû§ÊÇ·ñÒѵǼ¡£ÈôÊÇÄúÏë¹Ø±ÕÓû§µÇ¼£¬Ö»Ð轫¸ÃÖÐÐļþ´ÓÄúµÄÓ¦ÓóÌÐòÖÐɾ³ý¼´¿É¡£
ʾÀý´úÂ룺
// ¹Ø±ÕÑéÖ¤ÖÐÐļþ // Route::middleware(['auth'])->group(function () { // // ... your routes requiring authentication // });
µÇ¼ºó¸´ÖÆ
ÈôÊÇÄú²»Ïëɾ³ý Authenticate ÖÐÐļþ£¬Ò²¿ÉÒÔ½«Æä×¢Ê͵ô¡£ÕâÑù£¬¸ÃÖÐÐļþ²»»á±»ÆôÓ㬵«ÈÔ¿ÉËæʱ»Ö¸´Æ书Ч¡£
°ì·¨Èý£º×¢ÏúËùÓÐÄ¿½ñµÇ¼µÄÓû§
ÈôÊÇÄúÔڹرÕÓû§µÇ¼֮ǰ£¬ÒÑÓÐÓû§µÇ¼µ½ÄúµÄÓ¦ÓóÌÐòÖУ¬ÔòÓ¦¸Ã½«ÕâЩÓû§×¢Ïúµô¡£²»È»£¬ÕâЩÓû§»á¼ÌÐøͨ¹ýÒÑÓеĻỰ»á¼ûÓ¦ÓóÌÐò£¬´Ó¶øÈƹý¹Ø±ÕÓû§µÇ¼µÄÉèÖá£
Äú¿ÉÒÔÔÚÄúµÄ AuthenticatesUsers »ò LoginController ¿ØÖÆÆ÷ÖÐÌí¼Ó´úÂ룬ÒÔÈ·±£ÔÚ×¢ÏúËùÓÐÓû§Ö®Ç°ÇëÇóÖÐÖ¹£º
ʾÀý´úÂ룺
// ÔÚ AuthenticatesUsers ¿ØÖÆÆ÷µÄ logout ÒªÁìÖÐÌí¼ÓÒÔÏ´úÂë public function logout(Request $request) { $this->guard()->logout(); $request->session()->invalidate(); $request->session()->regenerateToken(); // ÖÐÖ¹ÇëÇó return response()->noContent(); }
µÇ¼ºó¸´ÖÆ
ÕâÑù£¬µ±ÓÐÓû§ÊµÑé×¢Ïúʱ£¬½«»á¶Ï¿ªÇëÇ󣬲¢×èÖ¹ÈκÎÈËÊéÃæ»á»°£¨Èç CSRF ÁîÅÆ£©¾ÙÐÐÈκÎÓÐÓòÙ×÷¡£
°ì·¨ËÄ£ºÉ¨³ý»á»°ºÍ Cookie
×îºó£¬ÔÚÍê³ÉÉÏÊö°ì·¨Ö®ºó£¬ÄúÓ¦¸Ãɨ³ýËùÓÐÏà¹ØµÄ»á»°ºÍ Cookie£¬ÒÔ±ÜÃâÒѾµÇ¼µÄÓû§¼ÌÐø»á¼ûÄúµÄÓ¦ÓóÌÐò¡£
ÔÚÄúµÄ Authenticate ÖÐÐļþ»òÆäËûÖÐÐļþÖУ¬¿ÉÒÔ½« SessionMiddleware ºÍ StartSession ÖÐÐļþ×¢²áΪÒÑͨ¹ýÖÐÐļþ£¬ÒÔÈ·±£ËùÓлỰ Cookie ¶¼±»É¨³ý£º
ʾÀý´úÂ룺
// ÔÚÄúµÄ Authenticate ÖÐÐļþ»òÆäËûÖÐÐļþÖÐɨ³ý»á»°ºÍ Cookie public function handle($request, Closure $next, ...$guards) { // ½ûÓÃËùÓлỰ²¢É¨³ýËùÓÐ Cookie $request->session()->flush(); $request->session()->regenerate(); $response = $next($request); $response->headers->remove('Set-Cookie'); return $response; }
µÇ¼ºó¸´ÖÆ
ÕâЩ´úÂ뽫ÔÚÇëÇó¿¢ÊÂʱÇå¿ÕËùÓлỰÊý¾Ý£¬²¢É¾³ýËùÓлỰ Cookie¡£ÕâÑù£¬×ÝÈ»ÓÐÈËÒâÍâµØʵÑé»á¼ûÄúµÄÓ¦ÓóÌÐò£¬ËûÒ²ÎÞ·¨Í¨¹ýÈκλỰ»Ö¸´ÆäÒѵǼ״̬¡£
×ܽá
¹Ø±ÕÓû§µÇ¼¿ÉÄܲ»ÊÇ Laravel Ó¦ÓóÌÐò¿ª·¢µÄ³£¼û×ö·¨£¬µ«ÔÚijЩÇéÐÎÏÂËüȷʵÓÐÓá£Òª¹Ø±ÕÓû§µÇ¼£¬ÔÚÄúµÄÓ¦ÓóÌÐòÖнûÓÃÓëÉí·ÝÑéÖ¤Ïà¹ØµÄ·ÓÉ¡¢ÖÐÐļþºÍ»á»° Cookie£¬È»ºó×¢ÏúËùÓÐÄ¿½ñµÇ¼µÄÓû§¡£ÕâÑù£¬×ÝÈ»ÓÐÈËʵÑéʹÓÃÓÐÓõĻỰÀ´»á¼ûÄúµÄÓ¦ÓóÌÐò£¬ËûÒ²ÎÞ·¨Í¨¹ýÈκλỰ»Ö¸´ÆäÒѵǼ״̬¡£
ÒÔÉϾÍÊÇlaravel ÔõÑù¹Ø±ÕÓû§µÇ¼µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡