HTTP Routing Example Tutorial (III) -- CSRF Attack Principle and Protection
1. What is a CSRF attack
2. How to avoid CSRF attacks in Larravel
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?> ">
<? php echo csrf_field(); ?>
{!! csrf_field() !!}
Route::get('testCsrf',function(){ $csrf_field = csrf_field(); $html = <<<GET <form method="POST" action="/testCsrf"> {$csrf_field} <input type="submit" value="Test"/> </form> GET; return $html; }); Route::post('testCsrf',function(){ return 'Success!'; });
Success!
Route::get('testCsrf',function(){ $html = <<<GET <form method="POST" action="/testCsrf"> <input type="submit" value="Test"/> </form> GET; return $html; });
3. Exclude specified URL from CSRF validation
<? php namespace App\Http\Middleware; use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier; class VerifyCsrfToken extends BaseVerifier { /** *Specify URLs excluded from CSRF validation * * @var array */ protected $except = [ 'testCsrf' ]; }
Success!
4. X-CSR F-Token and its use
<meta name="csrf-token" content="{{ csrf_token() }}">
$.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } });
5. X-XSRF Token and its use
6. Analysis of CSRF Verification Principle in Larravel
public function start() { $this->loadSession(); if (! $ this->has('_token')) { $this->regenerateToken(); } return $this->started = true; }
public function handle($request, Closure $next) { if ($this->isReading($request) || $this->shouldPassThrough($request) || $this->tokensMatch($request)) { return $this->addCookieToResponse($request, $next($request)); } throw new TokenMismatchException; }
Note:
tokensMatch The method starts with Request Get in
_token The parameter value is obtained if the request does not contain this parameter
X-CSRF-TOKEN The value of the request header. If the request header does not exist, get
X-XSRF-TOKEN The value of the request header. Note that
X-XSRF-TOKEN The value of the request header needs to be called
Encrypter Of
decrypt Method to decrypt.