Use Firebase Admin SDK for PHP with Laravel (token reacquisition)
Sep 8, 2020
PHP
Laravel
Firebase
#Firebase Admin SDK for PHP doesn’t seem to be able to get tokens automatically
For example, Javascript can be obtained with currentUser.getIdToken ()
as follows.
It is convenient because it automatically updates before the expiration date.
firebase.auth (). currentUser.getIdToken (/ * forceRefresh * / true) .then (function (idToken) {
// Send token to your backend via HTTPS
// ...
}) .catch (function (error) {
// Handle error
});
The Firebase Admin SDK for PHP didn’t have similar functionality. I don’t want to log in again every time the token expires.
Solution
// If you are not logged in
if (! Session :: get ('token')) {
$ signInResult = $ this-> auth-> signInAnonymously ();
Session :: put ('token', $ signInResult-> idToken ());
Session :: put ('refresh_token', $ signInResult-> refreshToken ());
}
// Token authentication
try {
$ auth-> verifyIdToken (Session :: get ('token'));
} catch (\ Exception $ e) {// It is better to narrow down to ExpiredToken here
// If it expires, reacquire it using the update token
$ refresh_token = Session :: get ('refresh_token');
$ signInResult = $ auth-> signInWithRefreshToken ($ refresh_token);
Session :: put ('token', $ signInResult-> idToken ());
}
The flow is as follows.
- There is
refresh_token
in the login result, so save it for a session or something. - When the token expires, an exception will be thrown with
verifyIdToken ()
, so get it again withsignInWithRefreshToken ()
Timing when refresh token is changed is not so much, so if you want to use it for the time being, I think that the above will be enough.