From 8057b7bc47dfa0dd0d174276b17e00ad8ecf5e17 Mon Sep 17 00:00:00 2001 From: crynobone Date: Tue, 8 Dec 2015 22:30:49 +0800 Subject: [PATCH] Add RequireCsrfToken. Signed-off-by: crynobone --- Middleware/RequireCsrfToken.php | 61 +++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Middleware/RequireCsrfToken.php diff --git a/Middleware/RequireCsrfToken.php b/Middleware/RequireCsrfToken.php new file mode 100644 index 0000000..38aaa80 --- /dev/null +++ b/Middleware/RequireCsrfToken.php @@ -0,0 +1,61 @@ +encrypter = $encrypter; + } + + /** + * Handle an incoming request. + * + * @param \Illuminate\Http\Request $request + * @param \Closure $next + * + * @return mixed + */ + public function handle($request, Closure $next) + { + if (! $this->tokensMatch($request)) { + throw new TokenMismatchException(); + } + + return $next($request); + } + + /** + * Determine if the session and input CSRF tokens match. + * + * @param \Illuminate\Http\Request $request + * + * @return bool + */ + protected function tokensMatch($request) + { + $token = $request->input('_token') ?: $request->header('X-CSRF-TOKEN'); + + if (! $token && $header = $request->header('X-XSRF-TOKEN')) { + $token = $this->encrypter->decrypt($header); + } + + return Str::equals($request->session()->token(), $token); + } +}