Get UID/accessToken while working with Firebase Authentication

What is Firebase?


Firebase is an all-in-one backend as a service provider (BaaS) that provides a database, authentication, and cloud storage among its many services

What is Authentication?

Firebase Authentication allows users to sign in to your app using different sign-in methods. In this tutorial, we will learn how to authenticate users using email and passwords to sign in to your app.

Login request 

In this tutorial, you’re going to learn how to use the Firebase Real-Time Database service in a React application.

How to get UID/accessToken from Firebase?

Auth data is asynchronous in Firebase. So you need to wait for the event to occur and then you have access the current logged in user’s UID. You won’t be able to get the other users’ UID. It will get called when the app opens too. You can also render your app only once when you receive the event.

What is UID?

The UID to assign to the newly created user. Must be a string between 1 and 128 characters long, inclusive. If not provided, a random UID will be automatically generated.

What is an access token?

A secure string that a client uses to access protected resources. An instance issues access tokens to clients that have a valid authorization grant. Each access token has a specific scope, lifespan, and other attributes. When a user logins in, the authorization server issues an access token. When a client application needs to access protected resources on a server on behalf of a user, the access token lets the client signal to the server that it has received authorization from the user to perform certain tasks or access certain resources.

Within your application, you can either save this user object or get the current user at any time with firebase.auth().currentUser.

import { getAuth, onAuthStateChanged } from “firebase/auth”; const auth = getAuth(); const user = auth.currentUser; if (user) { // The user object has basic properties such as display name, email, etc. // The user’s ID, unique to the Firebase project. Do NOT use const uid = user.uid; } ———————————-Or——————————- auth.onAuthStateChanged((user) => { if (user) { // User logged in already or has just logged in. const uid = user.uid; console.log(user.uid); } else { // User not logged in or has just logged out. } });

Now to call the method getIdToken() you need to get the access token (as mentioned in the below code):

import { getAuth, onAuthStateChanged } from “firebase/auth”; const auth = getAuth(); const getToken = await auth.currentUser?.getIdToken(); ————————–Or—————————- auth.onAuthStateChanged(function(user) { if (user) { console.log(user); // it shows details about user user.getIdToken().then(function(idToken) { console.log(idToken); // It is a firebase token }); } });

How to keep logged in after the token gets expired?

ID tokens expire one hour after creation. You cannot change this expiration time. Under the hood, the client SDKs refresh the ID token using a long-lived token we call a refresh token. The refresh token is used to generate a new ID token every hour which allows the client SDKs to continue to work seamlessly. The refresh token allows the client to stay logged in indefinitely until you call signOut() or a session invalidation event like a change in password or email happens from another client device. You don’t need to do anything to manage the ID token’s lifecycle. The client SDKs do all of that for you. 

Basically, you need to issue another token (it may be a JWT) and send both to the client. When the client needs to refresh the access token, it sends the refresh token to a special endpoint and gets a new access token (if the refresh token is valid).

What are Refresh Tokens?

It is a unique token that is used to obtain additional access tokens. This allows you to have short-lived access tokens without having to collect credentials every time one expires.

When you make a call from a browser .getIdToken(true) will automatically refresh your token. Make a call like this:

import { getAuth } from “firebase/auth”; const auth = getAuth(); const forceRefresh = true; const getToken = auth.currentUser?.getIdToken(forceRefresh) .then(function(idToken) { console.log(idToken); }) .catch(function(error) { console.log(error); });

How to make a custom hook for getting UID/AccessToken when we reload the page

Lastly, the onAuthStateChanged() method is called once upon page load and it will be called every time when auth state event occurs. Auth state events include a sign-in or a sign-out. Technically, the client SDKs will also fire onAuthStateChanged() every time a new ID token is minted, but this may be changing in an upcoming release so I wouldn’t rely too much on this behavior. Instead, I’d just call currentUser.getToken() whenever you need the latest fresh ID token. Every time the listener onAuthStateChanged() is called, it is passed to the current Firebase user. If this is null, there is no logged-in user. Otherwise, there is a logged-in user.

import { getAuth, onAuthStateChanged } from “firebase/auth”; import {useState, useEffect} from ‘react’ export default function useFirebaseToken() { const [token, setToken] = useState(”) const auth = getAuth(); useEffect(() => { onAuthStateChanged(auth, (user) => { if (user) { user.getIdToken(true) .then(latestToken => setToken(latestToken)) .catch(err => console.log(err)) } }) }, []) return token }

Hook for getting UID

import { getAuth, onAuthStateChanged } from “firebase/auth”; import {useState, useEffect} from ‘react’ export default function useFirebaseId() { const [id, setId] = useState(”); const auth = getAuth(); useEffect(() => { onAuthStateChanged(auth, (user) => { if (user) { const currentUserId = user.uid; setId(currentUserId); } else { // User is signed out // … } }); }, []); return id }

then use like so in your functional component

const token = useFirebaseToken() useEffect(() => { if (token) { // Write some message/code } }, [token])

Hope this article is helpful for you and you must have learned now Points to remember while working with Firebase Authentication in react js. Keep Learning & Keep Growing

Latest

SENTRY integration in your React Native App for Error/Crash tracking

Sentry captures data by using an SDK within your...

Recall the concepts of useCallback.

useCallback hook is one of the best hooks offered...

Value of Comments in the code!!

During my journey of Software Development, I am always...

YOLO:Bullet Paced Algorithm

http://sh017.hostgator.tempwebhost.net/media/33949d0e61af4b50f374c534713f56b3 According to world health organization, more than 1.35 million...

Featured

Developing Enterprise Application in Node.js – CJS Vs ESM

Node.js is a popular runtime environment for building server-side...

Integrating your web react applications with their React Native(android and IOS) apps using QR code

Integrating a web application with Android and iOS apps...

YOLO: Bullet Paced Algorithm – popular choice for object detection in autonomous vehicles 

According to world health organization, more than 1.35 million...

Importance of Test Scalar Tool

TestScalar is quick to access, convenient to execute, easy to track. Our popular web-based test planning software lets you focus on what matters: meeting...

From Requirements to Reporting: How to Use a Test Case Management Tool to Ace Your Software Testing

The Software Testing Life Cycle (STLC) is a process that describes the stages of testing software. It includes planning, design, execution, and reporting of...

YOLO:Bullet Paced Algorithm

http://sh017.hostgator.tempwebhost.net/media/33949d0e61af4b50f374c534713f56b3 According to world health organization, more than 1.35 million people die every year because of vehicle accidents . Vehicle safety features started with passive safety...

LEAVE A REPLY

Please enter your comment!
Please enter your name here