Home > database >  How to get a FireBase idToken on the server
How to get a FireBase idToken on the server

Time:04-13

According to the documentation, to verify the user role, you need to check the idToken of the current user. But where to get it? I just found the receipt on the client

I tried to do this:

app.get("/admin-cp", function (req, res) {
    const sessionCookie = req.cookies.session || "";
    
    admin
        .auth()
        .verifySessionCookie(sessionCookie, true  )
        .then((userData) => {
            console.log("Logged in:", userData.email)
            console.log('Авторизован. Доступ в админ панель открыт')

            const customToken = admin.auth().createCustomToken(userData.uid)
            admin
            .auth()
            .verifyIdToken(customToken)
            .then((claims) => 
            {  
                if (claims.admin === true) 
                {    
                    // Allow access to admin resource.   
                } 
            });

            res.sendFile(path.join(initial_path, "admin-cp/main-admin_cp.html"));
        })
        .catch((error) => {
            console.log('Не авторизован. Ошибка', error, ' отсутвует userData')
            res.redirect("/login");
        });
});
code: 'auth/argument-error',
message: 'First argument to verifyIdToken() must be a Firebase ID token string.'

CodePudding user response:

You should ideally pass the ID Token in your API request's headers from client side.

const idToken = await firebase.auth().currentUser.getIdToken()

const res = await fetch('/api-url', { headers: { authorization: idToken } })

Then you can read the token on server side:

const idToken = req.headers.authorization;

if (!idToken) return res.status(401).send("Unauthorized")

// verify token using verifySessionCookie() here 
  • Related