Hkm Sadek
Hkm Sadek

Reputation: 3209

How can I create and match CSRF token in vue 2 app and laravel

I am not using the vue 2 set up that laravel provides by default. Instead, I have two separates folders for the vue app and laravel api backend. The vue app is outside laravel project folder.

In this case, how can I implement CSRF ?

This is what I am thinking to do please let me know if this will work fine or there are more better ways to do.. 1. Set a cookie in vue app with some random long strings. 2. In every api calls, make sure the cookie is being sent. 3. In laravel backend, get this token from the request. 4. Get the token from the cookie itself. 5. Match the both cookie and if matches assume CSRF is valid..

Thanks in advance..

Upvotes: 4

Views: 865

Answers (1)

Benyi
Benyi

Reputation: 952

I was confusing, but I found answers by asking the community.

Just take a look at Laravel CSRF document, the framework stores XSRF-TOKEN as a key of cookie. And you need to do is to get the XSRF-TOKEN from cookie, then set the token as a part of header with X-XSRF-TOKEN: key_from_cookie, Laravel will decrypt the key as CSRF token as usual.

Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php
/**
 * 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;
}

Upvotes: 1

Related Questions