简体   繁体   中英

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..

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM