laravel È¥µôcsrf
laravelÊÇÒ»¿îÊ¢ÐеÄphp¿ò¼Ü£¬ÒѾ³ÉΪÁËרҵ¿ª·¢ÕߺͳõѧÕßÃDZ¸ÊÜÇàíùµÄÑ¡Ôñ¡£laravel¿ò¼ÜʵÏÖÁËcsrf±£»¤£¬ÊÇΪÁ˱ÜÃâ¿çÕ¾ÇëÇóαÔì¹¥»÷¡£È»¶ø£¬ÔÚijЩÇéÐÎÏ£¬ÓÐʱ¼äÐèҪȥµôcsrf±£»¤£¬±¾ÎĽ«´øÄãÏàʶÔÚlaravelÖÐÈ¥µôcsrf±£»¤µÄÒªÁì¡£
ʲôÊÇCSRF±£»¤
¿çÕ¾ÇëÇóαÔ죬ӢÎÄËõдΪCSRF£¬ÊÇÒ»ÖÖ³£¼ûµÄWeb¹¥»÷¡£¹¥»÷ÕßʹÓÃÊܺ¦ÈËÔڵǼ״̬ϵÄÉí·Ý£¬Î±ÔìÇëÇ󣬵ִï¶ñÒâ²Ù×÷µÄÄ¿µÄ¡£ÎªÁ˱ÜÃâÕâÖÖ¹¥»÷£¬LaravelʵÏÖÁËCSRF±£»¤¹¦Ð§£¬¿ÉÒԺܺõı£»¤WebÓ¦ÓóÌÐò¡£
LaravelÖÐCSRF±£»¤µÄʵÏÖ
LaravelÖÐʵÏÖCSRF±£»¤£¬Ö÷ÒªÊÇͨ¹ýÒÔÏÂÈý¸ö°ì·¨£º
2.1. ÌìÉúCSRF token
ÔÚHTML±íµ¥ÖÐÌí¼Ócsrf_fieldÖ¸ÁÕâ¸öÖ¸Áî»á×Ô¶¯ÌìÉúCSRF token£¬²¢Ìí¼Óµ½±íµ¥Òþ²ØÓòÖС£
<form> @csrf <input type="text" name="name"> <input type="submit" value="Submit"> </form>
µÇ¼ºó¸´ÖÆ
2.2. ÑéÖ¤CSRF token
ÔÚºó¶Ë£¬Laravel»áÑéÖ¤ÇëÇóµÄCSRF tokenÊÇ·ñÕýµ±¡£ÈôÊDz»Õýµ±£¬½«·µ»ØÒ»¸ö¹ýʧÐÅÏ¢¡£ÔÚLaravel 5.6¼°ÒÔºóµÄ°æ±¾ÖУ¬Ä¬ÈÏÌí¼ÓÁËCSRF±£»¤ÖÐÐļþ£¬ËùÓÐPostÇëÇ󶼻á¾ÙÐÐCSRFÑéÖ¤¡£ÈôÊÇÄúµÄÇëÇóûÓÐ׼ȷЯ´øCSRF token£¬½«»ñµÃÏÂÃæµÄ¹ýʧÐÅÏ¢£º
TokenMismatchException in VerifyCsrfToken.php line 68:
µÇ¼ºó¸´ÖÆ
2.3. ¿çÕ¾¾ç±¾¹¥»÷·À»¤
ΪÁ˱ÜÃâ¿çÕ¾¾ç±¾¹¥»÷£¬ÄúÓ¦¸Ã×ñÕՔתÒåÊä³ö”µÄÔÔò£¬²»ÒªÖ±½ÓÊä³öÓû§ÌṩµÄÊý¾Ý£¬¶øÓ¦¸Ã¶ÔÆä¾ÙÐд¦ÀíºóÔÙÊä³ö¡£ÀýÈ磬ʹÓÃhtmlentities»òhtmlspecialcharsº¯Êý½«HTMLÌØÊâ×Ö·û¾ÙÐÐתÒå¡£
ÒÔÉϾÍÊÇLaravelÖÐʵÏÖCSRF±£»¤µÄÒªÁì¡£ÏÂÃæÎÒÃǽ«ÏÈÈÝÔõÑùÈ¥µôÕâÖÖ±£»¤¡£
ÔõÑùÈ¥µôLaravelÖеÄCSRF±£»¤
ÈôÊÇÄúµÄWebÓ¦ÓóÌÐòÖУ¬²»ÐèÒª¾ÙÐÐCSRF±£»¤£¬ÄúÒ²¿ÉÒÔÈ¥µôLaravelÖеÄCSRF±£»¤¡£ÏÂÃæÎÒÃǽ«ÏÈÈÝÁ½ÖÖÈ¥µôCSRF±£»¤µÄÒªÁì¡£
3.1. ¹Ø±ÕCSRF±£»¤ÖÐÐļþ
ĬÈÏÇéÐÎÏ£¬LaravelËùÓеÄPostÇëÇ󶼻á¾ÙÐÐCSRFÑéÖ¤¡£ÈôÊÇÄúÏëҪȥµôÕâÖÖÑéÖ¤£¬¿ÉÒÔ½«CSRF±£»¤ÖÐÐļþ´ÓMiddlewareÖÐÈ¥µô¡£ÏêϸҪÁìÈçÏ£º
·¿ªapp/Http/Kernel.phpÎļþ£¬ÔÚ$middlewareGroupsÊý×éÖУ¬ÕÒµ½webÖÐÐļþ×飬½«[‘IlluminateFoundationHttpMiddlewareVerifyCsrfToken’]ÕâÆäÖÐÐļþ´Ó¸ÃÊý×éÖÐɾ³ý¼´¿É¡£
protected $middlewareGroups = [ 'web' => [ AppHttpMiddlewareEncryptCookies::class, // IlluminateSessionMiddlewareAuthenticateSession::class, // IlluminateRoutingMiddlewareSubstituteBindings::class, // IlluminateFoundationHttpMiddlewareVerifyCsrfToken::class, ], 'api' => [ 'throttle:60,1', 'auth:api', ], ];
µÇ¼ºó¸´ÖÆ
´Ëʱ£¬ËùÓеÄPostÇëÇ󶼲»»á¾ÙÐÐCSRF±£»¤ÑéÖ¤¡£ËäÈ»¿ÉÒÔÈ¥µôCSRF±£»¤£¬µ«ÕâÒ²´ú±í×ÅÒ»¶¨µÄÇ徲Σº¦¡£Òò´Ë½¨ÒéÖ»ÔÚÑÏ¿áµÄ²âÊÔÇéÐÎÏ¿ªÆô¡£
3.2. ÊÖ¶¯ºöÂÔCSRF±£»¤
ÈôÊÇÔÚÈ«¾Ö¹æÄ£ÄڹرÕCSRF±£»¤ÖÐÐļþ£¬Äú¿ÉÒÔÔÚÌض¨µÄ·ÓÉ»ò¿ØÖÆÆ÷ÖÐÊÖ¶¯ºöÂÔCSRF±£»¤ÑéÖ¤¡£ÏêϸҪÁìÈçÏ£º
ÔÚÐèÒª·ÅÐеÄ·ÓÉ»ò¿ØÖÆÆ÷ÒªÁìÖУ¬Ê¹ÓÃwithoutMiddlewareÒªÁì:
Route::post('route', function () { // })->withoutMiddleware([IlluminateFoundationHttpMiddlewareVerifyCsrfToken::class]);
µÇ¼ºó¸´ÖÆ
ÕâÖÖÒªÁì¿ÉÒÔÔÚijЩÌØÊâÇéÐÎÏÂʹÓ㬿ÉÊDz»½¨ÒéÔÚËùÓеÄ·Óɶ¼½ÓÄÉ´ËÒªÁì¡£
×ÛÉÏËùÊö£¬LaravelÖÐʵÏÖCSRF±£»¤ÊÇÒ»¸öºÜºÃµÄÇå¾²²½·¥£¬ÔÚ²»ÐëÒªµÄÇéÐÎÏ£¬²»½¨ÒéÈ¥µôCSRF±£»¤¡£ÈôÓÐÐèÒª£¬¿ÉÒÔͨ¹ýÒÔÉÏÒªÁìÈ¥µôCSRF±£»¤¡£ËäÈ»£¬ÔÚÏÖʵÏîÄ¿¿ª·¢ÖУ¬Çëƾ֤ÏÖÕæÏàÐÎÉóÉ÷ʹÓá£
ÒÔÉϾÍÊÇlaravel È¥µôcsrfµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡