Laravel 5: 在 VerifyCsrfToken 之外验证令牌

Laravel 5: validate token outside VerifyCsrfToken

我需要验证 Laravel 5 令牌,在 VerifyCsrfToken class,

之外

有没有办法从 Controller

调用 VerifyCsrfToken->handle

或使用任何不同的方式验证它们?

return (session('_token') == $variableYouNeedToCheck);

类似于,但具有时序安全比较:

use Symfony\Component\Security\Core\Util\StringUtils;
// ...
return StringUtils::equals(session('_token'), $variableYouNeedToCheck);

不要使用 == 来比较字符串,使用等同于 PHP 5.6 的 hash_equals()

的东西

请参阅下面的代码以获取有效的简单代码

use Illuminate\Support\Facades\Request;
class MyController extends Controller {

      public function getIndex(Request $request)
         if(hash_equals(request->get('myCSRFTokenFromMyFormOrAjax'), Session::token())){
             // token not matches please 
             //redirect or stop the application here 
         }
      }
 } 

我使用 hash_equals() 出于安全原因,有时不同值的哈希值可能相同

如果您不理解上面的代码,请阅读 Type hinting

另请注意,使用 Laravel5.0 it's better to create a middlewere to gain control on your code and Don't repeate a a peace of code everywhere Read this Worndefull article