×ðÁú¿­Ê±

laravel cookie Ìæ»»

laravelÊÇÒ»¸öʹÓÃÆÕ±éµÄphp¿ò¼Ü£¬ËüµÄcookie×é¼þÔÚweb¿ª·¢ÖÐÓÃÓÚ¸ú×ÙÓû§ÐÐΪ¡£È»¶ø£¬ÓÉÓÚÓû§µÄÒþ˽ÎÊÌ⣬²»ÉÙä¯ÀÀÆ÷¶¼×îÏÈÏÞÖƵÚÈý·½cookiesµÄʹÓá£ÎªÁ˱£»¤Óû§Òþ˽£¬laravelÍƳöÁ˼¸ÖÖcookieÌæ»»¼Æ»®£¬±¾ÎĽ«ÏÈÈÝÆäÖÐÁ½ÖÖ½ÏΪ³£¼ûµÄÒªÁì¡£

Ê×ÏÈ£¬ÎÒÃÇÀ´¿´¿´ÔõÑùʹÓÃLaravel×Ô´øµÄSession×é¼þÀ´Ìæ»»cookie¡£ÔÚĬÈÏÇéÐÎÏ£¬LaravelµÄSession×é¼þʹÓÃcookieÀ´´æ´¢Ä¿½ñ»á»°µÄID¡£¿ÉÊÇ£¬Äã¿ÉÒÔͨ¹ýÐÞ¸Äsession.phpÉèÖÃÎļþÖеÄdriverÑ¡ÏîÀ´¸Ä±äSessionµÄÇý¶¯ÀàÐÍ¡£Ä¬ÈÏÇéÐÎÏ£¬driverÑ¡ÏîµÄֵΪ”file”£¬ÌåÏÖSession»á½«Êý¾Ý´æ´¢ÔÚÎļþÖС£ÈôÊÇÄ㽫driverÑ¡ÏîµÄÖµ¸ÄΪ”database”£¬ÄÇôSession½«»á½«Êý¾Ý´æ´¢ÔÚÊý¾Ý¿â±íÖС£Í¨¹ýʹÓÃSession×é¼þ¶ø²»ÊÇcookie£¬Äã¿ÉÒÔ×èÖ¹Browser¶ÔµÚÈý·½µÄcookie¾ÙÐÐËæ»úɾ¼õ»ò¾Ü¾øµÄÎÊÌâ¡£

Æä´Î£¬Laravel»¹ÌṩÁËTokenGuardÀ´Ìæ»»cookie¡£TokenGuardÊÇLaravelÈÏÖ¤¿ò¼ÜµÄÒ»²¿·Ö£¬ËüÔÊÐíÓû§½«ÊÚȨÁîÅÆ´æ´¢ÔÚURLÖжø²»ÊÇcookieÖС£ÒªÊ¹ÓÃTokenGuard£¬ÄãÐèÒªÔÚAppServiceProviderÖÐŲÓÃAuth::viaRequest()ÒªÁ죬²¢ÇÒת´ïÒ»¸ö»Øµ÷º¯ÊýÀ´Æ¥ÅäÊÚȨÁîÅÆ¡£ÔÚÿ¸öÐèÒªÈÏÖ¤µÄ¿ØÖÆÆ÷ÒªÁìÖУ¬ÄãÐèÒª°ÑÊÚȨÁîÅÆ´ÓURLÖжÁÈ¡³öÀ´£¬²¢Å²ÓÃAuth::loginUsingId()ÒªÁìÀ´ÑéÖ¤Óû§Éí·Ý¡£

½ÓÏÂÀ´£¬ÎÒ½«ÎªÄú·ºÆðÒ»¸öÍêÕûµÄ´úÂëʾÀý£¬ÑÝʾÔõÑùʹÓÃTokenGuardÀ´Ìæ»»cookie¡£Ê×ÏÈ£¬ÎÒÃÇÐèÒªÐÞ¸ÄAppServiceProviderÖеÄAuth::viaRequest()ÒªÁ죺

public function boot()
{
    $this->registerPolicies();

    Auth::viaRequest('token', function ($request) {
        return User::where('api_token', $request->token)->first();
    });
}

µÇ¼ºó¸´ÖÆ

ÔÚÕâ¸ö»Øµ÷º¯ÊýÖУ¬ÎÒÃǽ«$token²ÎÊý´Ó$request¹¤¾ßÖжÁÈ¡³öÀ´²¢Ê¹ÓÃËü¾ÙÐÐÓû§Éí·ÝÑéÖ¤¡£ÈôÊÇÊÚȨÁîÅÆÇкÏÒªÇ󣬸ú¯Êý½«·µ»Ø¶ÔÓ¦µÄUserʵÀý£¬²»È»·µ»Ønull¡£

½ÓÏÂÀ´£¬ÔÚÎÒÃÇÐèÒªÈÏÖ¤Óû§Éí·ÝµÄ¿ØÖÆÆ÷ÒªÁìÖУ¬ÔÚÒªÁìÉùÃ÷´¦¼ÓÈëÒ»¸ö$request²ÎÊý£º

public function update(Request $request, $id)
{
    $user = Auth::guard('api')->user();

    if ($user && $user->id === $id) {
        // ...
    }
}

µÇ¼ºó¸´ÖÆ

È»ºó£¬ÎÒÃÇ¿ÉÒÔÔÚURLÖн«ÊÚȨÁîÅÆת´ï¸øRESTfulµÄupdateÒªÁ죬ÀýÈ磺/users/1?token=your-token¡£×îºó£¬ÎÒÃÇ¿ÉÒÔͨ¹ýŲÓÃAuth::loginUsingId()ÒªÁìÀ´Íê³ÉÓû§Éí·ÝÑéÖ¤£¬È·±£Óû§ÓÐȨÏÞ¸üжÔÓ¦µÄÓû§ÐÅÏ¢¡£

ʹÓÃTokenGuardÌæ»»cookieµÄÒªÁìºÜÊÇÎÞа£¬ÊÊÓÃÐÔ¹æÄ£ºÜÊÇÆձ顣³ýÁËTokenGuardÖ®Í⣬Laravel»¹Ö§³ÖʹÓÃOAuth2ºÍOpenID ConnectµÈ±ê×¼ÈÏ֤ЭÒ飬ÕâЩЭÒé¿ÉÒÔÌṩ¸üÇå¾²ºÍ¸üÎÞаµÄÌæ»»¼Æ»®¡£

×ÜÖ®£¬ºÏÀíʹÓÃSessionºÍTokenGuardÕâЩLaravelÌṩµÄÌæ»»¼Æ»®¿ÉÒԺܺõؽâ¾öcookie±»Ëæ»úɾ¼õºÍ¾Ü¾øµÄÎÊÌ⣬ͬʱҲÌá¸ßÁËÓû§Òþ˽±£»¤¡£ËäÈ»£¬Ã¿¸öÌæ»»¼Æ»®¶¼ÓÐ×Ô¼ºµÄÓÅÈõµã£¬ÐèҪƾ֤Ïêϸ³¡¾°¾ÙÐÐÑ¡ÔñºÍʹÓá£

ÒÔÉϾÍÊÇlaravel cookie Ìæ»»µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡

ÃâÔð˵Ã÷£ºÒÔÉÏչʾÄÚÈÝȪԴÓÚÏàÖúýÌå¡¢ÆóÒµ»ú¹¹¡¢ÍøÓÑÌṩ»òÍøÂçÍøÂçÕûÀí£¬°æȨÕùÒéÓë±¾Õ¾Î޹أ¬ÎÄÕÂÉæ¼°¿´·¨Óë¿´·¨²»´ú±í×ðÁú¿­Ê±ÂËÓÍ»úÍø¹Ù·½Ì¬¶È£¬Çë¶ÁÕß½ö×ö²Î¿¼¡£±¾ÎĽӴýתÔØ£¬×ªÔØÇë˵Ã÷À´ÓÉ¡£ÈôÄúÒÔΪ±¾ÎÄÇÖÕ¼ÁËÄúµÄ°æȨÐÅÏ¢£¬»òÄú·¢Ã÷¸ÃÄÚÈÝÓÐÈκÎÉæ¼°ÓÐÎ¥¹«µÂ¡¢Ã°·¸Ö´·¨µÈÎ¥·¨ÐÅÏ¢£¬ÇëÄúÁ¬Ã¦ÁªÏµ×ðÁú¿­Ê±ÊµÊ±ÐÞÕý»òɾ³ý¡£

Ïà¹ØÐÂÎÅ

ÁªÏµ×ðÁú¿­Ê±

13452372176

¿É΢ÐÅÔÚÏß×Éѯ

ÊÂÇéʱ¼ä£ºÖÜÒ»ÖÁÖÜÎ壬9:30-18:30£¬½ÚãåÈÕÐÝÏ¢

QR code
¡¾ÍøÕ¾µØͼ¡¿¡¾sitemap¡¿