Set httpOnly flag for CSRF token in Laravel
Asked Answered
B

3

12

I'm building an application in Laravel 5.1 for a client. After I finished the application I got back an pentest report which tells me to add a HttpOnly flag. I added 'secure' => true and 'http_only' => true to app/config/session.php. The httpOnly flag is set for all sessions, except the XSRF-TOKEN session. How am I able to set this flag as well?

Beyrouth answered 23/11, 2015 at 12:2 Comment(0)
C
23

You are able to overwrite the method addCookieToResponse($request, $response) in App\Http\Middleware\VerifyCsrfToken

/**
 * Add the CSRF token to the response cookies.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Illuminate\Http\Response  $response
 * @return \Illuminate\Http\Response
 */
protected function addCookieToResponse($request, $response)
{
    $response->headers->setCookie(
        new Cookie('XSRF-TOKEN',
            $request->session()->token(),
            time() + 60 * 120,
            '/',
            null,
            config('session.secure'),
            false)
    );

    return $response;
}

And do not forget to add

use Symfony\Component\HttpFoundation\Cookie;
Christachristabel answered 10/2, 2016 at 10:19 Comment(2)
If you want the httpOnly flag to be set to true, the last argument into Cookie() method must be true: $response->headers->setCookie( new Cookie('XSRF-TOKEN', $request->session()->token(), time() + 60 * 120, '/', null, config('session.secure'), true)Ax
For complete solution: github.com/laravel/framework/blob/5.3/src/Illuminate/Foundation/…Kramlich
R
1

This can be fixed. If you need http only for token add this to VerifyCsrfToken middleware:

/**
 * 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'], true, false, $config['same_site'] ?? null
        )
    );

    return $response;
}
Runstadler answered 24/3, 2020 at 8:33 Comment(0)
E
1

You must use in .env

SESSION_DOMAIN=
SESSION_SECURE_COOKIE=true
SESSION_HTTP_ONLY=true
SESSION_SAME_SITE=strict
Eridanus answered 30/6, 2021 at 11:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.