HTTP Routing Example Tutorial (III) -- CSRF Attack Principle and Protection


 Avoiding CSRF attacks in Laravel

1. What is a CSRF attack

CSRF is an abbreviation for Cross site Request Forgery. For the CSRF attack principle and its protection, you can check this item on Github: Understanding CSRF , which is quite detailed and thorough.

2. How to avoid CSRF attacks in Larravel

Avoiding CSRF attacks in the Larvel framework is simple: Larvel automatically generates a CSRF token for each user session, which can be used to verify whether the login user and the initiator are the same person. If not, the request fails.

Laravel provides a global help function csrf_token To obtain the token value, simply add the following HTML code to the view submission chart form to bring the token to the request:

 <input type="hidden" name="_token" value="<?php echo csrf_token(); ?> ">

This code is equivalent to the global help function csrf_field Output of:

 <? php echo csrf_field(); ?>

stay Blade template engine It can also be called in the following ways:

 {!! csrf_field() !!}

Test code

We define the following code in routes.php:

 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!'; });

In the browser, we enter http://laravel.app:8000/testCsrf , click the "Test" button, and the browser outputs:

 Success!

This indicates that the request is successful. Otherwise, if we define the GET route as follows:

 Route::get('testCsrf',function(){ $html = <<<GET <form method="POST" action="/testCsrf"> <input type="submit" value="Test"/> </form> GET; return $html; });

Click the "Test" button to throw TokenMismatchException Exception.

3. Exclude specified URL from CSRF validation

Not all requests need to avoid CSRF attacks, such as requests to obtain data from third-party APIs.

You can use the VerifyCsrfToken app/Http/Middleware/VerifyCsrfToken.php middleware Add request URLs to exclude to $except In the attribute array:

 <? 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' ]; }

So we refresh the page http://laravel.app:8000/testCsrf Click the "Test" button in the page, the page will not report errors, and the normal output is as follows:

 Success!

4. X-CSR F-Token and its use

What if you submit a POST form using Ajax? We can set Token in meta:
 <meta name="csrf-token" content="{{ csrf_token() }}">

Then set it in this way in global Ajax X-CSRF-Token Request header and submit:

 $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } });

Laravel's VerifyCsrfToken Middleware will check X-CSRF-TOKEN For the request header, if the value is equal to the CSRF value in the session, the verification passes; otherwise, the verification fails.

5. X-XSRF Token and its use

In addition, Larravel will save the value of CSRF to the file named XSRF-TOKEN In the cookie, and then VerifyCsrfToken The middleware verifies this value. Of course, we don't need to do any manual operations. Some JavaScript frameworks such as Angular will automatically help us to implement it.

6. Analysis of CSRF Verification Principle in Larravel

Having said so many usage methods, let's analyze the source code to see how the bottom layer of Laravel can avoid CSRF attacks:

1) First, when Larravel starts the session, a token value will be generated and stored in the session( Illuminate\Session\Store.php Line 90 start Method), the corresponding source code is as follows:

 public function start() { $this->loadSession(); if (! $ this->has('_token')) { $this->regenerateToken(); } return $this->started = true; }

2) Then focus on the analysis VerifyToken Middleware handle Method, in which first pass isReading Method to determine the request method. If the request method is HEAD GET OPTIONS For one, CSRF verification is not required;

3) Re adoption shouldPassThrough Method to determine whether the request route is in $excpet The attribute array is excluded, and if excluded, no verification is performed;

4) Finally passed tokensMatch Method to determine whether the CSRF TOKEN value in the request parameter is equal to the Token value in the session. If it is equal, it passes the verification. Otherwise, it throws TokenMismatchException Exception.

The corresponding source code is as follows:

 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.

give the thumbs-up Cancel Like Collection Cancel Collection

<<Previous: HTTP Routing Instance Tutorial (II) - Routing Naming and Routing Grouping

>>Next: Middleware Instance Tutorial - Creation and Use of Middleware and Definition of Middleware Parameters