Using firebase jwt to authenticate users to external server\service? - firebase

Okay so in my iOS app I log the user into firebase, then get the jwt token. So now I have my server with an api which accepts an idtoken in the header of the GET.
What do I do here? Certainly I wouldn't be validating the JWT againt firebase on every single API call right? I mean its fast, but that adds latency with a second external check, no? How does one simply just decode that guy in C#? I have an Auth0 layer already and that decodes the JWT with my server-stored secret, but that same code doesn't work for the Firebase token.
Could it just be decoded then extract the user details from that, maybe just check expiry and if expiry > X months it's still okay?

In order to verify Firebase ID tokens and JWTs in general, you only make a network call on your server to get the public certs which are usually not updated for several hours. You could cache that and try to verify with an ID token and if it fails, only then, load the new public certs.
And yes, you must verify the ID token on each call especially since Firebase ID tokens expire after typically an hour and need to be refreshed continuously.

Related

AWS Cognito expired access token

In my application I have used aws cognito with next auth for user auth.
In the jwt callback that I have from api next-auth I receive an access token, which is then saved and sent to the client side. There, I save it in local storage and, among other things, I send it to my api which checks if it is correct.
The problem is that after an hour the access token expires and does not get a new one (always next-auth gives me old value). Has anyone had a similar flow and knows how to manage a session refresh? I will add that I am not automatically logged out because next-auth is managing it underneath, but it does not return the value of the new access token to me.
Do you have any ways how to manage this?
I can suggest a workaround that would take the least effort to solve this quickly. Amazon Cognito contains 3 kinds of tokens, the ID Token, Access Token and Refresh Token.
From the Amazon Cognito console, you can increase the validity of the token you're dealing with from there. A good idea is to refer to this answer.
Albeit you might need a couple of methods to assert security and robustness.

FCM Token - When should I store/save it on my DB?

I am not sure what a proper FCM token handling mechanism would be so I’m writing our process down here just to get some validation or suggestions for improvements:
Fetch FCM token on client Login (Flutter)
Save FCM token on our Database (Using our REST API)
Delete FCM token on Logout (Using our REST API)
Q1: Should we be getting the FCM token more often than just on login? AFAIK, FCM token only changes on app re-installs, clearing cache, etc. Does this also include app-updates from the PlayStore? In that case, should we save the FCM token on every app launch since the user will remain logged in after an app update and hence we wouldn't trigger the save FCM call.
Q2: Did I mention the right way to handle deleting FCM tokens from our DB? We don’t want the user to keep getting notifications once they have logged out.
Q3: An add-on idea is to send the device_id to the server along with the fcm_token so that server deletes all previously saved FCM tokens for that device_id. This is useful to not have useless tokens on the DB from cases where the user uninstalls the app without logging out (which means that the DELETE fcm_token call never went through.)
The FCM token is refreshed under conditions that you don't control, and those conditions have even changed over time. To handle token updates properly, you'll need to implement both initially getting the token and then monitoring for token updates.
Note that FCM tokens are not associated with a user. It is fine if you want to associate them with a user, but it's up to your application code in that case to maintain the association. So that for example includes deleting the token from your database when the user signs out, as you're doing in step 3. 👍
For keeping your token registry clean, you can indeed do this proactively as you intend, or reactively as shown here: https://github.com/firebase/functions-samples/blob/master/fcm-notifications/functions/index.js#L76-L88
Hi Rohan fundamentaly you should use below logic to save tokens on server.
Step1:
as soon as you get token in callback whether new or same try to save it localstorage.
Step2:
Call your REST API to save it to your server. it is upto you if you want to send unique user identifier along with the token.
Step3:
It is obvious you will recieve token callback a lot of time so you can check whether you have similar token in localstorage, it means you have the token on the server so no point calling REST API.
Step 4: Now your app can send events back to server and based on it trigger Push notifications to the users.
Step 5: You can Add/update user token based on uniqye user identifier. In some cases a user can be guest user, so your app should generate guest userId and link it with token.
Stay safe.

Firebase Cloud Messaging (WebPush) token expiration handling

As I found out in Firebase source, every token has an expiration time of one week. And because messaging().onTokenRefresh is not implemented now, I'm assuming that there is no way of sending webpush-notifications to users that haven't been on my website with configured FCM for a week or longer.
Or my assumption is incorrect and this expiration exists only on browser side? And tokens on the server-side of FCM aren't expiring without a call from browser to recreate token?
It's not an actual expiration, but just a way to update the token information on Firebase servers. If the token is still valid (and it most likely is), updateToken method will return the same token, and it will keep working.
If you get a different token after a getToken call, you can safely overwrite the previous token in your server.

What does Firebase server side verifyIdToken() do under the hood?

I'm considering to use Firebase to perform identity verification. I am new to JWT, so my apologies if this is an obvious question, but I don't understand how the verification is actually done. It seems that FirebaseAuth.getInstance().verifyIdToken(idToken) works asynchronously, as the result is obtained via a listener. I understand that some certificates are used as described here, and that those certificates are rotated regularly. Does it mean that networking is required between my back-end server and Firebase server's each time I will call verifyIdToken()? Isn't it a problem ?
In order to verify Firebase ID tokens, the Firebase Auth public certs need to be retrieved (network request) and these are rotated on a regular basis. These are needed to ensure the Id token has not been tampered with. The JWT is first parsed, the algorithm to encrypt the token is checked to see if it matches the expected one, the signature is then verified using the public key obtained, finally the JWT claims are validated ensuring the token has not expired.

Firebase signInWithCustomToken handle token expiry

I'm using firebase 9.x with custom authentication. According to the documentation the token expiry cannot be more than one hour. Is there a listener which I can register to that will be called when the token expires.
The documentation also talks about automatic refreshing of tokens. I believe that is not applicable for custom authentication. Let me know otherwise.
https://firebase.google.com/docs/auth/server#use_the_firebase_server_sdk
Ideally the documentation (above) should have the requested information.
Thanks in advance.
The token that is generated server side (custom auth) is a JWT (JSON Web Token). This token must be supplied by your client (Android?) to the Firebase server to authenticate the user to Firebase. In the 9.x libraries, it seems these tokens now have a maximum life of an hour (i.e they are no longer accepted after 60 mins). (See Sam Stern's comment in this issue: https://github.com/firebase/quickstart-android/issues/31).
Sam indicates that once authentication has occurred using a custom generated token, the Android client will remain authorised until signed out.
If you actually require to know when your JWT token is valid until, it should be 60 minutes after you generate it on your server. If the token has not yet been used for auth with Firebase, at this point you could regenerate a new one and use that instead.
The documentation is misleading. It should say you have 1 hour to use the custom token to sign in. I also feel if the token is that temporary, then it should be single use. Otherwise it is confusing how they want you to use the token.
The SDK will take care of keeping the sessions tokens up to date IF YOU ARE SETUP correctly. For more info The custom tokens are only used to start a SESSION. So you have to have hour to use a custom token to SIGN IN. Once you are signed in and your Firebase Admin account and app configuration is setup correctly, the SDK can communicate back and forth with the Firebase back-end to keep the tokens up to date. Once you sign out with FirebaseAuth.signout(), you will need a new custom token to sign back in if it has been over 1 hour.
So in most cases, you really do not need to listen for token expiration
have you tried AuthListener?
mAuthListener = new FirebaseAuth.AuthStateListener(){
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
user.getCurrentUser().getToken(true);
// ...
}
};;
mAuth.addAuthStateListener(mAuthListener);

Resources