123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- <?php
-
-
-
-
-
-
-
-
-
-
-
-
-
- namespace app\common\middleware;
-
- use think\exception\HttpResponseException;
- use think\facade\Session;
-
- class FormTokenCheck
- {
-
-
- public function handle($request, \Closure $next, string $token = null)
- {
- $check = $this->checkToken($request, $token ?: '__token__');
- $_token = $request->token();
- if (false === $check) {
- $result = [
- 'code' => -1,
- 'msg' => '令牌错误',
- 'data' => ['__token__' => $_token],
- 'url' => '',
- ];
- throw new HttpResponseException(json($result));
- }
- return $next($request);
- }
-
-
-
- public function checkToken($request, string $token = '__token__', array $data = [])
- {
- if (in_array($request->method(), ['GET', 'HEAD', 'OPTIONS'], true)) {
- return true;
- }
- if (!Session::has($token)) {
-
- return false;
- }
-
- if ($request->header('X-CSRF-TOKEN') && Session::get($token) === $request->header('X-CSRF-TOKEN')) {
-
- Session::delete($token);
- return true;
- }
- if (empty($data)) {
- $data = $request->post();
- }
-
- if (isset($data[$token]) && Session::get($token) === $data[$token]) {
-
- Session::delete($token);
- return true;
- }
-
- Session::delete($token);
- return false;
- }
- }
|