Why haven't you used Laravel Sanctum?
Cookie::queue() not creating a cookie for API login
I'm using passport with Laravel 7 to login in and store a refresh token in a cookie:
class AuthController extends Controller
{
const REFRESH_TOKEN = 'refreshToken';
public function login(Request $request)
{
$request->validate([
'username' => 'required|email',
'password' => 'required',
]);
return $this->proxy('password', [
'username' => $request->username,
'password' => $request->password,
]);
}
public function refresh(Request $request)
{
$refreshToken = $this->request->cookie(self::REFRESH_TOKEN);
return $this->proxy('refresh_token', [
'refresh_token' => $refreshToken
]);
}
public function proxy($grantType, array $data = [])
{
$data = array_merge($data, [
'client_id' => config('services.passport.client_id'),
'client_secret' => config('services.passport.client_secret'),
'grant_type' => $grantType
]);
$response = Request::create(route('passport.token'), 'POST', $data);
$handleResponse = app()->handle($response);
$data = json_decode($handleResponse->getContent());
// Create a refresh token cookie
Cookie::queue(
self::REFRESH_TOKEN,
$data->refresh_token,
864000, // 10 days
null,
null,
false,
true // HttpOnly
);
return response('hello world')->withCookie(cookie(self::REFRESH_TOKEN));
return [
'access_token' => $data->access_token,
'expires_in' => $data->expires_in
];
}
}
Cookie::queue() in my proxy() method aren't storing a cookie.
It tried the solution from this stack overflow question
Cookie queuing is not enabled for api requests, this is the reason why it didn't work.
Open file App/Http/Kernel.php add the line \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, in protected $middleware array as displayed in above code snippet and test again it should work now.
This solution didn't work for me.
I don't know how to implement the second solution:
In case anyone fond their way here by Google, one way for cookie inclusion to silently fail is if you're explicitly defining your domain variable in its creation, and forgot to remove the "http://" from the beginning of it first. That's not the case with OP, but it was what brought me here. ;)
Maybe that's it? Any help would be awesome
Please or to participate in this conversation.