How to sync firebase users across several locations? (extension + website) - firebase

I'm working on chrome extension (provides main functionality) and the complementary website (mostly profile and billing related functionality) both backed with firebase backend.
I'm wondering if it's possible to implement the below scenario:
user logs in with the extension using firebase authentication (with firebaseUI lib)
I store a token that I can use to reauthenticate that user (is there such a token?)
when user opens the website, I login that user automatically with the token.
While both the extension and the website has their login/signup forms I'm wondering if it's possible to login user in the extension and to somehow automatically login that same user on the website so they don't have to enter their credentials twice?
So far I was hoping that I could use something like below:
firebase.auth().currentUser.getIdToken(true).then(function(idToken) {
console.log("idToken = ", idToken)
})
And then to use that idToken like this, since if I understand correctly, it's an AWT:
firebase.auth().signInWithCustomToken(idToken).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.log("signInWithCustomToken: error = ", error)
})
But it gives the following error:
code: "auth/invalid-custom-token"
message: "The custom token format is incorrect. Please check the documentation."
I can parse the token on https://jwt.io/ which shows all the user information but in the end it says "invalid signature"
So I guess this token can be only used to check authentication (like admin.auth().verifyIdToken(idToken)) but not to login user. Am I right?
I know I can create a custom token, but is there any straightforward way to workaround that and to login user from one place only using firebase funstionality? (of course without storing username/password)

You can't sign in with a Firebase ID token. What you can do is the following:
Keep the user session in the chrome extension and run all authenticated requests from there. Use postMessage (with origin verification) to talk with extension from app anytime a request is to be sent. With this you don't have to worry about session synchronization and no Firebase tokens are stored or passed to the web app or every web app that can access the extension.
Add a postMessage API to get an ID token from the extension after verifying the origin of the request. You can then send the request from the web app with the ID token. (less secure than 1 but easier to implement and session is stored in one place).
Create an HTTP endpoint that takes an ID token and returns a custom token. This would verifyIdToken and then create a corresponding custom token for that user using createCustomToken provided by Admin SDK. You then postMessage that from chrome extension to the web page after verifying origin and signInWithCustomToken with that custom token in that web app. This is the least secure as you are providing an endpoint to exchange a short lived ID token with an indefinite session. You will also deal with synchronization issues (user signs out from chrome extension, you have to sign out from websites, etc).

Related

Next Auth + Firebase - Change user password using firebase Rest API

I am working on project using Next JS + NextAuth package. For user authentication we are using NextAuth with Custom Credentials provider. I am making a sign in REst API request to Firebase to get the user logged in and saving all necessary bits like Firebase tokens(access and refresh) in JWT.
The flow works.
Where i am stuck: Changing user password.
Password change is pretty straight forward using firebase client SDK. But I am using Firebase API:
https://firebase.google.com/docs/reference/rest/auth#section-change-password
the flow to change password requires:
Provide latest access token in API request above.
If the latest Access token is not provided, the API would send back error like: TOKEN TOO OLD or RE AUTHENTICATE
So this to work, we need to reauthenticate the user prior to making that change password request.
What I have managed to do:
When user request password change, user needs to provide current password.
Using the current password, i would re sign in user using API end point:
https://firebase.google.com/docs/reference/rest/auth#section-sign-in-email-password
This would work but now I need to update the latest access token in the JWT using NextAuth.
At this point i am stuck:
Refreshing the JWT using Next Auth; as soon as the user is re-signed-in and again when password is changed and new access token is sent back from Firebase.
When I try to refresh the JWT with new access token (etc) token using NextAuth client side callback: https://next-auth.js.org/tutorials/refresh-token-rotation
The application breaks due to access tokens are not synced on JWT and on firebase.
Questions:
Is my flow correct changing the user password?
Is there better way of doing this?
Any help is appreciated. Thanks

Firebase admin - get Google OAuth token

I have a web application where users can sign in with Google.
To the sign-in process, I add a scope to be able to access Google Calendar.
Now that the user is signed in, I would like to - in server-side - get their current Google access token in order to make a request and get a list of their events.
Is there a way to get the current OAuth token (no need for refresh token) in order for me to make this completely on the server-side?
I'd say that you can check this article and put special attention to the recommendation for websites.
I understand you have configured already the consent screen, which is the first step of the basic steps on using OAuth 2.0. So I understand that you only have to perform the following steps:
Obtain an access token from the Google Authorization Server
Examine scopes of access granted by the user.
Send the access token to an API
I think you can also give a look to this other doc for more GCP insights over your goal to authorize the request using user tokens
Edited:
Regarding the Firebase Authentication, I understand this happens at the user's device, and you could use some code to retrieve the token and then send it to your back end servers as mentioned in here.
As a sample here there's the sample code for retrieving the token in Android:
FirebaseUser mUser = FirebaseAuth.getInstance().getCurrentUser();
mUser.getIdToken(true)
.addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
public void onComplete(#NonNull Task<GetTokenResult> task) {
if (task.isSuccessful()) {
String idToken = task.getResult().getToken();
// Send token to your backend via HTTPS
// ...
} else {
// Handle error -> task.getException();
}
}
});
A little about OAuth 2.0
Whenever a user signs up to your app/website via Google or 3rd Party, an Authorization Code, this Authorization Code is exchanged for an AccessToken & RefreshToken.
The AccessToken sent via Google are valid generally for 60 minutes.
Offline Access (Server Side)
Let's break it down to two parts:
If your need to update within 60 minutes of user's last activity
You can use firebase along with gapi to achieve that. You'll be provided with the AccessToken that can be sent back to server to add to calendar.
More info on implementation
If you need to update after 60 minutes of user's last activity
Firebase & gapi's most method handle the AuthorizationCode flow internally. They even further refresh the AccessToken after 60 minutes. This is beneficial for most developers as they won't have a headache of managing all the tokens.
This method but, hides RefreshToken & AuthorizationCode from the developer. That is even if your server has the access token, it won't be able to refresh it and it would be deemed useless.
To achieve complete offline access, in the initial request to get AuthorizationCode you will need to send a HTTP GET parameter access_type to offline
GAPI provides you with grantOfflineAccess() method which returns the AuthorizationCode that can be later used on your server to fetch access token & refresh token.
Note: If you are storing AuthorizationCode in your database, make sure it is secure. The limitation in Firebase are set due to security reason. It is more secure to not talk with AuthorizationCode generally.
More links
https://developers.google.com/identity/protocols/oauth2/web-server
https://developers.google.com/identity/sign-in/web/reference
https://developers.google.com/identity/sign-in/web/server-side-flow
https://developers.google.com/identity/sign-in/web/backend-auth
Retrieve Google Access Token after authenticated using Firebase Authentication

Firebase - Custom oAuth2 service - Authorization code?

There is an app that wants to authenticate with my users using oAuth2.
So they open a window, with the authorize URL, and parameters (such as redirect uri)
Like: https://my-website.com/api/authLauncherauthorize?redirect=SOME_URI
Now I have my own firebase-login, and when the user logs in, I get their access token from firebase. Which is what I want to respond with.
However, in oAuth2 guides/explanations like https://aaronparecki.com/oauth-2-simplified/ I see I am supposed to return an authorization code, and I don't understand where can I get that from?
What I can do, is generate a bullshit code, pair it in the DB to the access token, and then in the "token" request, send the correct access token. Is that what I am supposed to do?
Just to be clear, this is my first time writing an oAuth2 service myself.
OAuth is a system that provides authenticated access to resources. This resource can be for example a user page or editing rights to that user page. So your goal is to provide access to permissions to the right people.
When someone logs in, they get a token. Your part is to generate that token however you want, may it be some form of userdata into base64 or completely random. Take this token and link it against permissions, like viewing a page, editing it or even simpler things like viewing the email of a user.
OAuth2 tokens and/or permissions should be revokable without deleting a user. You should not use OAuth2 to identify someone.
If I am understanding your question correctly:
User visits some website
User wants to register or login using your websites OAuth2
You redirect back to the original page and send your generated token
The page can access content on your site with this token
Assuming you are the Host Site, given a User who wants to connect a 3rd party application, then the flow would be like this:
User lands on site - Clicks Login with Github
User is redirected to Github site where they login and click "Authorize"
Github redirects user back to your site /authorize with an auth token.
Your site then passes that token back to the 3rd party API (github in this case) in exchange for an access token and refresh token.
You can then pass that Authorization token to an API endpoint to get details about it. If the token expires, you can use the refresh token to get a new Auth token. Both Tokens should be stored in your database for your user.
However writing that all out I realize you are asking how do you generate the Authorization token, so I'm guessing you're actually the 3rd party API in this example. So you would want to generate an Authorization token using a random generator. Since you are using firebase, you'll probably wanna try out their token generator: https://github.com/firebase/firebase-token-generator-node
There's also some more up-to-date info here I believe: https://firebase.google.com/docs/auth/admin/#create_a_custom_token
And like you said, you would store that in a database associated with the user, and then when the Host Site sends that user's auth token to your server, you exchange it for the Authorization token (and refresh token if requested).
It's also worth reading through how google does it, because you'd be doing something similar: https://developers.google.com/identity/protocols/OAuth2UserAgent#validatetoken
JWT is another option of generating tokens: https://jwt.io/

does firebase custom authentication require that you manage refresh tokens for web clients?

For firebase, I'm using custom authentication because our organization uses CAS for single sign on.
Does custom authentication handle refresh jwt tokens automatically or would I need to develop a refresh workflow within my app?
I am not creating custom tokens using a third party library. My token is created via var token = firebase.auth().createCustomToken(uid, additionalClaims) as described on https://firebase.google.com/docs/auth/server/create-custom-tokens. But this page doesn't mention anything about refresh tokens.
My clients are mainly web, and I've found notes that if you use the Android SDK, this refresh happens automatically. But I'm unsure about refresh tokens and web clients for custom authentications.
After you create the custom token using createCustomToken, you pass that token to the web client and call firebase.auth().signInWithCustomToken(token). The promise returned will resolve with a firebase User. The onAuthStateChanged listener will trigger as expected. A firebase Id token will be available. The token will be refreshed every hour and will be handled by the Firebase SDK. Anytime you call a user method or getToken on user, the token will be automatically refreshed if the old one was expired.

How to persist Firebase simple login authentication for a multipage WebApplication

I have been using firebase chat and firepad for real time functionality in My Web Application which has multiple pages like a forum.
I started using the Firebase SimpleLogin too.I am able to login as a user and get the auth object which has the uid,id etc info.
1)Now if the user traverses to another page(i.e a new url(same application) is loaded ),does the authentication persist ? Ofcourse as we are manually doing the authentication by calling ref.login(),how can we know if the user is logged in when the second page is loaded.Will firebase store any cookie in user's browser or local storage ?
2)If the user is authenticated through firebase and now for for any request to my backend server for a new page ,how will I know that the user is authenticated.Should I be manually handling this by inserting some cookie in the browser or a hidden form field once firebase login happens ?
3)Is firebase Authentication suitable for multi page web application where the html pages and content are served from a back server other than firebase.?
I have checked the below question too.
Firebase JWT Authentication, Continually Send Token?
As long as browser cookies and local storage are both local storage is available on the browser, Firebase Simple Login sessions will be persisted across page refreshes on the same domain. Simply reinstantiate the Firebase Simple Login client via new FirebaseSimpleLogin(ref, function(error, user) { ... }) to restore a persisted session, if one is available.
Using this approach, your callback will automatically be invoked with the login state of the user. Note that you do not need to call .login(...) again to pick up a session, as calling .login(...) will always try to create a new session.
Once the user is authenticated, you can begin writing Firebase Security Rules, making use of the auth variable, which is non-null for any authenticated user, and will contain useful user information (such as user ids) when using Firebase Simple Login. See the 'After Authenticating' section of any Simple Login auth. provider page to see the exact payload.
In the event that you already have an authentication system you'd like to integrate with Firebase, or Simple Login is not sufficient for your needs, you can always generate Custom Tokens with your own custom data. These tokens can contain any arbitrary JSON payload of your choosing, which will be available in your Firebase security rules under the auth variable.
See the Firebase Security Quickstart for more information.

Resources