I didn't make it clear in the project before csrf token Use , If it leads to a request , Keep asking for failure , Let's take a look at it today csrf Something about .

1.Cross-site request forgery Cross-site request forgery , Also known as “one click attack” perhaps session riding, Commonly abbreviated as CSRF perhaps XSRF, Is a malicious use of the site .CSRF To exploit a trusted site by masquerading as a request from a trusted user .

2. It can be understood from the literal meaning : When you visit  fuck.com  When hacking a page , There's a button or a form on the page ,URL/action by  http://you.com/delete-myself, This leads or forces or even forges users to trigger buttons or forms . In the browser GET or POST On request , It will take it with it  you.com  Of cookie, If the website doesn't do CSRF Defensive measures , So this request is  you.com  It seems to be perfectly legal , That would be right for  you.com  There's data corruption .

3. Third party malicious websites can also be constructed post Request and submit to , therefore POST Mode submission just raises the threshold of attack , Can't guard against CSRF attack , So for post We should also take precautions

About csrf For more information, please refer to  https://segmentfault.com/q/1010000000713614 https://www.ibm.com/developerworks/cn/web/1102_niugang_csrf/

stay laravel In order to prevent csrf attack , Designed  csrf token

laravel The default is on csrf token Verified , How to turn off this function :

(1) Open file :app\Http\Kernel.php

Comment out this line :‘App\Http\Middleware\VerifyCsrfToken’

(2) Open file  app\Http\Middleware\VerifyCsrfToken.php

modify handle Method is :

 public function handle($request, Closure $next)
{
// Use CSRF
//return parent::handle($request, $next);
// Ban CSRF
return $next($request);
}

csrf Use :

(1) stay html Add the :

 <input type="hidden" name="_token" value="{{ csrf_token() }}" />

(2) Use cookie The way , take app\Http\Middleware\VerifyCsrfToken.php It is amended as follows :

 <?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier; class VerifyCsrfToken extends BaseVerifier { /**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
return parent::addCookieToResponse($request, $next($request));
} }

Use cookie Method does not need to add this to every page input Of hidden label

It can also be used partially csrf The detection part is not used .

notes : This paper starts from laravel Of csrf token Let's start here :http://blog.csdn.net/proud2005/article/details/49995389

About  laravel Of csrf For more information, please refer to laravel College documents :http://laravelacademy.org/post/6742.html

Let's talk about our project about csrf token Use :

In another article, I also mentioned the use process in our project

 In middleware VerifyCsrfToken.php The revised content is :
 protected function tokensMatch($request)
{
// If request is an ajax request, then check to see if token matches token provider in
// the header. This way, we can use CSRF protection in ajax requests also.
$token = $request->ajax() ? $request->header('X-CSRF-TOKEN') : $request->input('_token');
return $request->session()->token() == $token;
} public function handle($request,\Closure $next){
//todo: After adding login authentication , Cancel
// That's what it's all about post Don't do it when you ask csrf token verification
if($request->method() == 'POST')
{
return $next($request);
} return parent::handle($request,$next);
}
 And then in vue Medium bootstrap.js Introduced in axios Add 
  window.axios.defaults.headers.common = { 'X-CSRF-TOKEN': document.querySelector('meta[name="X-CSRF-TOKEN"]').content, 'X-Requested-With': 'XMLHttpRequest' }; 
stay index.blade.php Add 
  <meta name="X-CSRF-TOKEN" content="{{csrf_token()}}"> 

The above code is easy to understand , Is to get csrf_token token , And then submit , After middleware verification

Let's focus on  VerifyCsrfToken.php middleware

There should be only one Middleware in the beginning handle function : This is all going on csrf token verification

 public function handle($request,\Closure $next){
return parent::handle($request,$next);
}

Now the content of this middleware in the project

 <?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
class VerifyCsrfToken extends BaseVerifier
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
//
];
// protected $except = [
//
// '/classroom_upload',
// 'wk_upload',
// 'wechat',
// ];
protected function tokensMatch($request)
{
// If request is an ajax request, then check to see if token matches token provider in
// the header. This way, we can use CSRF protection in ajax requests also.
$token = $request->ajax() ? $request->header('X-CSRF-TOKEN') : $request->input('_token');
return $request->session()->token() == $token;
} public function handle($request,\Closure $next){
//todo: After adding login authentication , Cancel
if($request->method() == 'POST')
{
return $next($request);
} return parent::handle($request,$next);
}
}

Let's take a look  VerifyCsrfToken.php Source code          Illuminate\Foundation\Http\Middleware\VerifyCsrfToken.php;

 <?php
namespace Illuminate\Foundation\Http\Middleware;
use Closure;
use Carbon\Carbon;
use Illuminate\Foundation\Application;
use Symfony\Component\HttpFoundation\Cookie;
use Illuminate\Contracts\Encryption\Encrypter;
use Illuminate\Session\TokenMismatchException; class VerifyCsrfToken
{
/**
* The application instance.
*
* @var \Illuminate\Foundation\Application
*/
protected $app; /**
* The encrypter implementation.
*
* @var \Illuminate\Contracts\Encryption\Encrypter
*/
protected $encrypter; /**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = []; /**
* Create a new middleware instance.
*
* @param \Illuminate\Foundation\Application $app
* @param \Illuminate\Contracts\Encryption\Encrypter $encrypter
* @return void
*/
public function __construct(Application $app, Encrypter $encrypter)
{
$this->app = $app;
$this->encrypter = $encrypter;
} /**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*
* @throws \Illuminate\Session\TokenMismatchException
*/
public function handle($request, Closure $next)
{
if (
$this->isReading($request) ||
$this->runningUnitTests() ||
$this->inExceptArray($request) ||
$this->tokensMatch($request)
) {
return $this->addCookieToResponse($request, $next($request));
} throw new TokenMismatchException;
} /**
* Determine if the HTTP request uses a ‘read’ verb.
*
* @param \Illuminate\Http\Request $request
* @return bool
*/
protected function isReading($request)
{
return in_array($request->method(), ['HEAD', 'GET', 'OPTIONS']);
} /**
* Determine if the application is running unit tests.
*
* @return bool
*/
protected function runningUnitTests()
{
return $this->app->runningInConsole() && $this->app->runningUnitTests();
} /**
* Determine if the request has a URI that should pass through CSRF verification.
*
* @param \Illuminate\Http\Request $request
* @return bool
*/
protected function inExceptArray($request)
{
foreach ($this->except as $except) {
if ($except !== '/') {
$except = trim($except, '/');
} if ($request->is($except)) {
return true;
}
} return false;
} /**
* Determine if the session and input CSRF tokens match.
*
* @param \Illuminate\Http\Request $request
* @return bool
*/
protected function tokensMatch($request)
{
$token = $this->getTokenFromRequest($request); return is_string($request->session()->token()) &&
is_string($token) &&
hash_equals($request->session()->token(), $token);
} /**
* Get the CSRF token from the request.
*
* @param \Illuminate\Http\Request $request
* @return string
*/
protected function getTokenFromRequest($request)
{
$token = $request->input('_token') ?: $request->header('X-CSRF-TOKEN'); if (! $token && $header = $request->header('X-XSRF-TOKEN')) {
$token = $this->encrypter->decrypt($header);
} return $token;
} /**
* Add the CSRF token to the response cookies.
*
* @param \Illuminate\Http\Request $request
* @param \Symfony\Component\HttpFoundation\Response $response
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function addCookieToResponse($request, $response)
{
$config = config('session'); $response->headers->setCookie(
new Cookie(
'XSRF-TOKEN', $request->session()->token(), Carbon::now()->getTimestamp() + 60 * $config['lifetime'],
$config['path'], $config['domain'], $config['secure'], false
)
); return $response;
}
}

among app Below VerifyCsrfToken Middleware is the one that inherits the source code VerifyCsrfToken class

We rewrote it in our project tokensMatch Method , Then tune the parent class. handle When , Is used in the parent class this call tokensMatch Of , What I feel should be useful in the end is the method we rewrite , If it is ajax If you ask , We'll test it $request->header('X-CSRF-TOKEN') And session Medium token Whether or not the same Otherwise , On the test $request->input('_token') And session Medium token Whether or not the same .

I am right. laravel I don't know how it works , If there's anything wrong with the above , Welcome to advise .

If you need to reprint, please indicate :

Source of this article :http://www.cnblogs.com/zhuchenglin/p/7723997.html

laravel Of csrf token Learn more about and use more related articles

  1. sqlmap and burpsuite Bypass csrf token Conduct SQL Injection detection

    utilize sqlmap and burpsuite Bypass csrf token Conduct SQL Inject Please quote source for reprint :http://www.cnblogs.com/phoenix--/archive/2013/04/12/30 ...

  2. CSRF token Cannot be verified . ----Yii After connecting to the database, the database error log reports an error

    CSRF token Cannot be verified . I'm using mongodb+ yii1.1 What is CSRF, please see the details here.  http://en.wikiped ...

  3. Django backstage post In the request csrf token

    Use Requests Libraries operate their own Django Site ,post land admin Page back 403,serverlog Show csrf token not set. csrf token yes get When you log in to the page, the server places c ...

  4. django rest framework csrf failed csrf token missing or incorrect

    django rest framework csrf failed csrf token missing or incorrect REST_FRAMEWORK = { 'DEFAULT_AUTHEN ...

  5. django CSRF token missing or incorrect

    django Prompt on asynchronous request 403 According to the general situation, the problem of authority ,python There is no problem with the documents , Take a close look at response There is a sentence in the dictionary CSRF token missing or incorrect. This must be because of ANN ...

  6. utilize sqlmap and burpsuite Bypass csrf token Conduct SQL Inject ( turn )

    problem :post We encountered the problem of csrf token Block of , as a result of csrf It's disposable , Failure to test . Solution :Sqlmap coordination burpsuite, Here is the detailed process , According to the experience of foreign scholars blog( however ...

  7. What is the best way to handle Invalid CSRF token found in the request when session times out in Spring security

    18.5.1 Timeouts One issue is that the expected CSRF token is stored in the HttpSession, so as soon a ...

  8. About django1.7.7 Use ajax Later “CSRF token missing or incorrect” The solution to the problem

    Recently used Python3.3.25 and django1.7.7 Development company project , In the use of ajax Come on post Data time , I've been reminding you all the time :403 error , as a result of “CSRF token missing or incorrect” ...

  9. CodeIgniter Use in CSRF TOKEN A pit of

    This is how it happened , An automated scanning tool says that there is... In my code XSS Loophole , What is? XSS If you don't understand, you can look here Open it in my code CodeIgniter Framework of the CSRF Token, as follows : It's simple , For more details, please refer to CI Officer, ...

Random recommendation

  1. LeetCode 368

    Title Description : Given a set of distinct positive integers, find the largest subset such that every pair (Si, S ...

  2. ios pyudaren

    ed2k://|file|%E9%A1%B9%E7%9B%AE%E6%8D%95%E9%B1%BC%E8%BE%BE%E4%BA%BA01.rmvb|67044010|9e013987298d7900 ...

  3. iOS Development —— Baidu cloud push

    Because the company project is an integrated Aurora push , See the next blog . Integrated Baidu push is about the same , It's best to refer to the official document integration , Official documents or official website tutorials are the best blogs . Baidu Push service SDK User's Manual (iOS edition ) http://push. ...

  4. javascript Keyword highlighting and linking

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" " http://www.w3.org/TR/html4/str ...

  5. Mobile Frequently asked questions iOS Under the Fixed + Input When calling the keyboard fixed Solutions to invalid problems

    Use iScroll when ,input And so on can't input content solution <script> function allowFormsInIscroll(){ [].slice.call(document.q ...

  6. github pages Build a website ( 3、 ... and )

    One . Personal site visit https:// user name .github.io Steps to build (1) Create personal site -> New warehouse ( notes : Warehouse name must be [ user name .github.io]) (2) New under warehouse index.htm ...

  7. golang interface A type variable is used as a concrete type

    such as , We define a struct type person struct { Name string `json:"name"` Age int `json:"age&q ...

  8. to singer To the left of fixedTitle, And show the scroll up offset effect ;

    1. What will be written dom Absolute positioning to the top : 2.dom The value is singerlist Of currentIndex.title( Get by calculating properties ), If yes, it will be displayed fixedTitle, If not, hide : 3. Calculation diff: When d ...

  9. java— Repeatedly read - Achieve elimination

    Achieve elimination 1.Chess.java package Linkup; /** * Chess packing class * * @author laixl * */ public class Chess { // The image state ...

  10. leetcode 576. Out of Boundary Paths

    leetcode 576 The meaning of the question is probably in one m*n In the grid , The coordinates are [i,j] Put an object on your grid , At the appointed time N(t<=N) in , How many ways to move objects out . Objects can only move up and down, left and right , Move one space at a time , Move ...