laravelÔõô·Àcsrf
laravelÊÇÒ»¿îÊ¢ÐеÄphp¿ò¼Ü£¬ËüÌṩÁËÐí¶àÊÊÓù¤¾ßºÍÇå¾²²½·¥£¬Ê¹µÃ¿ª·¢Ö°Ô±¿ÉÒÔÇáËɵع¹½¨¸ß¼¶webÓ¦ÓóÌÐò¡£ÆäÖУ¬±ÜÃâ¿çÕ¾ÇëÇóαÔ죨csrf£©¹¥»÷ÊÇÒ»¸öºÜÊÇÖ÷ÒªµÄÇå¾²²½·¥¡£ÔÚ±¾ÎÄÖУ¬ÎÒÃǽ«ÏÈÈÝlaravelÖÐÔõÑùÓÐÓõرÜÃâcsrf¹¥»÷¡£
ʲôÊÇCSRF¹¥»÷£¿
ÔÚÉîÈëÏàʶLaravelÔõÑù±ÜÃâCSRF¹¥»÷֮ǰ£¬ÏÈÀ´ÏàʶһÏÂCSRF¹¥»÷ÊÇʲô¡£CSRF¹¥»÷£¨Cross-Site Request Forgery£©£¬Ò²³ÆΪ¡°one-click attack¡±»ò¡°session riding¡±£¬ÊÇÒ»ÖÖÍøÂç¹¥»÷ÊÖÒÕ£¬¹¥»÷ÕßʹÓÃÓû§ÔÚÒÑÈÏÖ¤ÍøÕ¾ÉϵĻỰȨÏÞ£¬ÔÚÓû§²»ÖªÇéµÄÇéÐÎÏÂÖ´Ðв»·¨²Ù×÷¡£¼ò¶øÑÔÖ®£¬¾ÍÊǹ¥»÷Õßͨ¹ýÓÕÆÓû§ÔÚÒ»¸öÍøÕ¾ÉÏÖ´ÐвÙ×÷£¬´Ó¶ø¾ÙÐв»·¨×ªÒÆ×ʽð»òÕß͵ȡÓû§µÄÃô¸ÐÐÅÏ¢µÈÐÐΪ¡£
CSRF¹¥»÷µÄÔÀí²¢²»Öش󣬹¥»÷ÕßÔÚÒ»¸öÍøÕ¾ÉÏαÔìÒ»¸ö±íµ¥»òÕßÁ´½Ó£¬ÆäÖаüÀ¨ÁËÖ´ÐÐһЩΣÏÕ²Ù×÷µÄÇëÇó¡£È»ºó£¬¹¥»÷Õß»áÓÕʹÓû§µã»÷»òÕßÌá½»ÕâЩαÔìµÄ±íµ¥£¬µ±Óû§Ö´ÐÐÕâЩ²Ù×÷ʱ£¬¹¥»÷Õß¾ÍÄܹ»Ê¹ÓÃÕâ¸öʱ»úÇÔÈ¡Óû§µÄÐÅÏ¢£¬²¢Ö´ÐÐһЩ²»·¨²Ù×÷¡£
Ôõô±ÜÃâCSRF¹¥»÷£¿
LaravelÌṩÁËһЩ±ÜÃâCSRF¹¥»÷µÄÒªÁ죬ÒÔÏÂÊÇһЩ³£ÓõÄÒªÁ죺
CSRFÁîÅÆ
LaravelʹÓÃCSRFÁîÅÆÀ´±ÜÃâCSRF¹¥»÷£¬¸ÃÁîÅÆ»áÔÚ±íµ¥Ìύʱ·¢ËÍ£¬²¢ÇÒ»áÔÚЧÀÍÆ÷¶Ë¾ÙÐÐÑéÖ¤¡£LaravelÔÚÿ¸öÓ¦ÓóÌÐòÖÐΪ±íµ¥ºÍAJAXÇëÇóÌṩÁËÒ»°ÑÆæÒìµÄÁîÅÆ£¬¿ÉÒÔ½«¸ÃÁîÅÆǶÈëµ½±íµ¥ºÍAJAXÇëÇóÖУ¬µ±ÇëÇó±»·¢Ë͵½Ð§ÀÍÆ÷ʱ£¬Laravel»áÑéÖ¤¸ÃÁîÅÆÊÇ·ñÓëÓ¦ÓóÌÐòÖеÄËæ»úÌìÉúÁîÅÆÆ¥Åä¡£ÈôÊÇÆ¥ÅäÀֳɣ¬ÇëÇó¾Í»á±»´¦Àí¡£
ÔÚLaravelÖУ¬¿ÉÒÔͨ¹ýʹÓÃcsrf_field()º¯Êý£¬À´ÌìÉúÒ»¸ö°üÀ¨CSRFÁîÅƵÄÒþ²Ø×ֶΣ¬¸Ã×ֶοÉÒÔ±»Ç¶Èëµ½±íµ¥ÖС£ÀýÈ磺
<form action="/your/url" method="POST"> {{ csrf_field() }} <!-- ÆäËû±íµ¥×ֶΠ--> </form>
µÇ¼ºó¸´ÖÆ
X-CSRF-TokenÍ·
ÔÚʹÓÃAJAX·¢ËÍPOSTÇëÇóʱ£¬¿ÉÒÔÔÚÇëÇóÍ·ÖÐÌí¼ÓX-CSRF-Token×ֶΣ¬¸Ã×ֶΰüÀ¨CSRFÁîÅÆ£¬Laravel»áÕë¶Ô¸ÃÇëÇóÍ·¾ÙÐÐÑéÖ¤¡£
ÀýÈ磺
$.ajaxSetup({ headers: { 'X-CSRF-Token': $('meta[name="_token"]').attr('content') } });
µÇ¼ºó¸´ÖÆ
CSRFÑéÖ¤ÖÐÐļþ
ÔÚLaravelÖУ¬Í¨¹ýCSRFÑéÖ¤ÖÐÐļþ£¬¿ÉÒÔΪÿ¸öPOST£¬PUT£¬PATCH»òDELETEÇëÇóÇ¿ÖƾÙÐÐCSRFÑéÖ¤¡£ÈôÊÇÇëÇóÖÐδ°üÀ¨×¼È·µÄCSRFÁîÅÆ£¬ÇëÇ󽫻ᱻ¾Ü¾ø£¬²¢·µ»ØÒ»¸öHTTP 419״̬Âë¡£
ΪÁËÆôÓÃCSRFÑéÖ¤ÖÐÐļþ£¬ÔÚÖÐÐļþ×éÖÐÌí¼ÓCSRFÖÐÐļþ¼´¿É¡£
// app/Http/Kernel.php protected $middlewareGroups = [ 'web' => [ // ÆäËûÖÐÐļþ IlluminateFoundationHttpMiddlewareVerifyCsrfToken::class, ], // ÆäËûÖÐÐļþ×é ];
µÇ¼ºó¸´ÖÆ
×¢ÖØ£ºCSRFÁîÅÆÔÚÿ´ÎÇëÇóʱ¶¼»á±¬·¢×ª±ä£¬ÒÔÊÇÔÚ¾ÙÐÐAjaxÇëÇóʱ£¬ÐèÒªÖØÖÃÇëÇóÍ·ÖеÄX-CSRF-Token×ֶΣ¬²»È»»áÔì³ÉÑé֤ʧ°Ü¡£
×ܽá
LaravelΪ¿ª·¢Ö°Ô±ÌṩÁËÇ¿Ê¢µÄ¹¤¾ßºÍÇå¾²²½·¥£¬À´±ÜÃâCSRF¹¥»÷¡£Í¨¹ýʹÓÃCSRFÁîÅÆ¡¢X-CSRF-TokenÍ·ºÍCSRFÑéÖ¤ÖÐÐļþ£¬¿ÉÒÔÓÐÓõرÜÃâCSRF¹¥»÷£¬±£»¤Óû§µÄÐÅÏ¢Çå¾²¡£ÔÚʹÓÃLaravel¾ÙÐÐWeb¿ª·¢Ê±£¬ÎñÐëҪעÖØÇå¾²ÎÊÌ⣬²¢Æð¾¢Ñ°ÕÒ²¢Ó¦ÓÃÖÖÖÖÇå¾²²½·¥£¬ÒÔÈ·±£ÍøÕ¾ºÍÓû§µÄÐÅÏ¢²»Êܵ½¹¥»÷ºÍÍþв¡£
ÒÔÉϾÍÊÇlaravelÔõô·ÀcsrfµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡