Laravel CSRF 代币

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22877117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:45:54  来源:igfitidea点击:

Laravel CSRF Token

laravelcsrf

提问by Gabriel Matusevich

EDIT: I should have said this at the start, I'm using AngularJS in the FronEnd, and I'm making all the request via XHR. I'm developing an Application using CSRF Tokenfor every user request.

编辑:我应该在开始时说这个,我在 FronEnd 中使用 AngularJS,我通过 XHR 发出所有请求。我正在开发一个CSRF Token用于每个用户请求的应用程序。

Should I regenerate the Tokenafter each request?

我应该Token在每个请求之后重新生成吗?

Something like

就像是

Session::forget("_token") and Session::put("_token", RANDOM_SOMETHING)

Or is it enough to use the same one each user Session?

或者每个用户使用相同的就足够了Session

Is there any benefit?

有什么好处吗?

回答by madarasz

With Laravel 5 using Blades templates, it's pretty easy.

Laravel 5 使用 Blades 模板,这很容易。

If you only want the value of the csrf token, you can generate it by writing:

如果你只想要 csrf 令牌的值,你可以通过编写它来生成它:

{{ csrf_token() }}

which generates the token value like this:

它生成这样的令牌值:

7YC0Sxth7AYe4RFSjzaPf2ygLCecJhPbyXhz6vvF


If you are using forms, you can add the following line of code inside the form:

如果您使用的是表单,则可以在表单中添加以下代码行:

{{ csrf_field() }}

which will generate html like this:

这将生成这样的 html:

<input type="hidden" name="_token" value="7YC0Sxth7AYe4RFSjzaPf2ygLCecJhblahblah">

回答by duellsy

Laravel should be doing this for you, you don't need to manage the creation / deletion of _token

Laravel 应该为你做这件事,你不需要管理创建/删除 _token

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

See the 'CSRF Protection' section in the docs here: http://laravel.com/docs/security

请参阅此处文档中的“CSRF 保护”部分:http: //laravel.com/docs/security

回答by Joyal

If you are using Laravel 5.6, do the following at the top of forms to create hidden input field for the CSRF token

如果您使用的是 Laravel 5.6,请在表单顶部执行以下操作,为 CSRF 令牌创建隐藏输入字段

  @csrf

回答by hlev

Depends. If the attacker is not MITM, in the sense that they cannot eavesdrop on traffic between your web app and the API server, a single CSRF token for the entire session should be enough.

要看。如果攻击者不是 MITM,从某种意义上说,他们无法窃听您的 Web 应用程序和 API 服务器之间的流量,则整个会话的单个 CSRF 令牌就足够了。

Assuming you guard sensitive operations on the server-side too (i.e. allow access to resources only to the owner of the resource, e.g. "delete my account", etc.) the token would ensure that the browser making the request is the legitimate, authenticated user's browser. That's all you should worry about, I think.

假设您也在服务器端保护敏感操作(即仅允许资源所有者访问资源,例如“删除我的帐户”等),令牌将确保发出请求的浏览器是合法的、经过身份验证的用户的浏览器。这就是你应该担心的,我想。

On the other hand, if the attacker is capable of looking at non-secure traffic between the web app and your API, they may get hold of the CSRF token and your session_id and do evil stuff transparently. In such case granting, using and subsequently discarding a token for each request (POST, or any kind that does sensitive operation) only makes their job a bit more difficult, but you're still doomed.

另一方面,如果攻击者能够查看 Web 应用程序和您的 API 之间的非安全流量,他们可能会获得 CSRF 令牌和您的 session_id 并透明地做坏事。在这种情况下,为每个请求(POST 或任何执行敏感操作的类型)授予、使用和随后丢弃令牌只会使他们的工作更加困难,但您仍然注定要失败。

My 2 cents...

我的 2 美分...

回答by Paresh Barad

CSRF token prevents Cross-Site attack by comparing cookie token with server token.

CSRF 令牌通过将 cookie 令牌与服务器令牌进行比较来防止跨站点攻击。

You can generate csrf token in laravel by csrf_token()helper function. If you want full csrf fields then you can use csrf_field()function and csrf internal logic is

您可以通过csrf_token()辅助函数在 Laravel 中生成 csrf 令牌。如果你想要完整的 csrf 字段,那么你可以使用csrf_field()function 和 csrf 内部逻辑是

function csrf_field()
{
   return new HtmlString('<input type="hidden" name="_token" value="'.csrf_token().'">');
}

When new request will generate then laravel create random token every time and store in browser cookie and session after stored Its compare to each other like cookie == session token

当新请求将生成时,laravel 每次都会创建随机令牌,并在存储后存储在浏览器 cookie 和会话中,它们相互比较,例如 cookie == session token

Laravel Internal logic is following and you can find it in VerifyCsrfTokenMiddleware.

Laravel 内部逻辑如下,你可以在VerifyCsrfToken中间件中找到它。

/**
 * 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(), $this->availableAt(60 * $config['lifetime']),
            $config['path'], $config['domain'], $config['secure'], false, false, $config['same_site'] ?? null
        )
    );

    return $response;
}

回答by Mr Talha

If you want to get the CSRF Token in the controller so you can just use it like this and redirect the post Route

如果你想在控制器中获取 CSRF 令牌,那么你可以像这样使用它并重定向 post Route

$CSRFToken = csrf_token();

Easy Peasy Hope it helps you

Easy Peasy 希望对你有帮助