21

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 Token for every user request.

Should I regenerate the Token after each request?

Something like

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

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

Is there any benefit?

4
  • What are you using the token for? Assuming you are using it for something other than preventing XSS, its hard to say if it will be "good" enough for your scenario. Commented Apr 5, 2014 at 6:02
  • @itachi Laravel's CSRF token is used to prevent cross-site requests (typically XSS). It is a token saved to the website's session and sent with every form submission, so a form must be submitted from the website with the session to have the correct session..rather than faking a request with cross-site scripting. Commented Apr 5, 2014 at 6:18
  • 2
    @Sam yup. but CSRF and XSS are two very different aspect. having a token will help you in csrf but not in xss. Commented Apr 5, 2014 at 6:21
  • @itachi fair enough, thanks for pointing that out. My explanation was pretty subpar, but the point still stands (in my opinion) that we need to know the OP's intention for using the CSRF token to secure his application. Commented Apr 5, 2014 at 6:22

6 Answers 6

43

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

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

{{ 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:

<input type="hidden" name="_token" value="7YC0Sxth7AYe4RFSjzaPf2ygLCecJhblahblah">
Sign up to request clarification or add additional context in comments.

Comments

17

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

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

See the 'CSRF Protection' section in the docs here: https://laravel.com/docs/10.x/csrf#

2 Comments

Im using AngularJS in the FronEnd, im sending the CSRF Token on each XHR Request, im not handling it the regular way
I have tried using Session::token() and other methods for retrieving the token, but Laravel doesn't renegerates the Token, My question was IF I SHOULD REGENERATE the Token or simply use the same one on the entire session
10

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

  @csrf

Comments

7

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.

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.

My 2 cents...

3 Comments

This answer should be accepted by the OP since it's the only one that actually tries to answer his question.
@hlev you are very right. so what do you suggest?
@r89human The same as before. TLS (HTTPS) and a single token for the user session should be enough for most purposes. Refer to the OWASP cheat sheet for a more thorough overview. cheatsheetseries.owasp.org/cheatsheets/…
3

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

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

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 Internal logic is following and you can find it in VerifyCsrfToken Middleware.

/**
 * 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;
}

1 Comment

Good answer with example, Thanks
2

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

$CSRFToken = csrf_token();

Easy Peasy Hope it helps you

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.