Alexxosipov
Alexxosipov

Reputation: 1234

Can't set cookie for api route laravel

Doing an service with backend (laravel) and frontend SPA (vue.js, vue-cli 3). I need to make an auth via httpOnly cookie (not localStorage). I use tymondesigns/jwt-auth as api auth package.

My environment is:

My login route is /api/auth/login, controller method is:

public function login()
    {
        $credentials = request(['email', 'password']);
        $user = User::where('email','=',$credentials['email'])->first();
        if (!$user || !$token = auth()->claims(['sub' => $user->id, 'csrf-token' => str_random(32) ])->attempt($credentials)) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }
        return response()
            ->json('success')
            ->withCookie('token', $token, config('jwt.ttl'), ".brideplanner.test", null, false, false);
    }

But when I try to send an request to the API, there's no token item in the cookie storage. What's wrong here? Why there's no token? What should I do?

UPD: I tested the request via postman and I got the token:

Set-Cookie →token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9icmlkZXBsYW5uZXIudGVzdFwvYXBpXC9hdXRoXC9sb2dpbiIsImlhdCI6MTU1MTM5NDMwNCwiZXhwIjoxNTUxMzk1MjA0LCJuYmYiOjE1NTEzOTQzMDQsImp0aSI6Im9uU1NtWEpSU0prR3NKc3giLCJzdWIiOjEsInBydiI6Ijg3ZTBhZjFlZjlmZDE1ODEyZmRlYzk3MTUzYTE0ZTBiMDQ3NTQ2YWEiLCIwIjoic3ViIiwiMSI6ImNzcmYtdG9rZW4iLCJjc3JmLXRva2VuIjoiTE9jSDFCWG9ITFJBMjlFYTg2MG1XQXhrVnpTR2gzT2oifQ.mnR4C6bwMIVptU64eZ6tN-gCYyFEuCIk_dm6dJsXrLY; expires=Thu, 28-Feb-2019 23:06:44 GMT; Max-Age=900; path=.brideplanner.test; domain=.brideplanner.test; httponly

But when I send the request from my SPA (http://app-test.brideplanner.test:81/), it goes wrong.

Upvotes: 3

Views: 8469

Answers (1)

ceejayoz
ceejayoz

Reputation: 180055

In a default Laravel install, the api routes do not have the middleware (Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse) enabled that handles cookies.

You can enable this middleware on your API routes, if you really need cookie-based auth, but be sure to read up on the differences.

Upvotes: 5

Related Questions