kreait / firebase-php

Unofficial Firebase Admin SDK for PHP
https://firebase-php.readthedocs.io/
MIT License
2.28k stars 433 forks source link

HTTP-only, secure cookie #931

Closed ronlinet closed 2 months ago

ronlinet commented 2 months ago

Describe the feature you would like to see

Anybody ever tried cookie stored tokens with AJAX refresh calls ?

Server Side PHP scenario:

if (\Auth::check()) {
    $serviceAccount = ServiceAccount::fromJsonFile(storage_path() . '/services.json');
    $firebase = (new Factory)->withServiceAccount($serviceAccount)->create();
    $token = $firebase->getAuth()->createCustomToken(\Auth::user()->email . ' WEB API');

    // Set the token in an HTTP-only, Secure cookie
    setcookie("firestoreToken", $token, [
        'expires' => time() + 3600,  // Token valid for 1 hour
        'path' => '/',               // Accessible across the whole domain
        'secure' => true,            // Only send over HTTPS
        'httponly' => true,          // Not accessible via JavaScript
        'samesite' => 'Strict'       // Cookie only sent to the same site
    ]);

    return true;
} else {
    return false;
} 

Client side Ajax:


// Refresh the token 5 minutes before expiry (after 55 minutes)
setInterval(() => {
    // Make an AJAX call to your server to refresh the token
    fetch('/refresh-token', { method: 'GET' })
        .then(response => {
            if (response.ok) {
                console.log('Token refreshed');
            } else {
                console.error('Failed to refresh token');
            }
        })
        .catch(error => console.error('Error:', error));
}, 55 * 60 * 1000); // 55 minutes