Search code examples
javascriptfirebasefirebase-authenticationsession-cookiesfirebase-cli

firebase authentication: signInWithCustomToken and createSessionCookie - error auth/invalid-id


I am trying to implement a login mechanism using Firebase custom token and session cookies, for sure I am doing something wrong but I cannot figure it out.

I will put my code and then explain how I am using it to test it.

Frontend code

const functions = firebase.functions();
const auth = firebase.auth();

auth.setPersistence(firebase.auth.Auth.Persistence.NONE);

auth.onAuthStateChanged((user) => {
    if (user) {
        user.getIdToken()
            .then((idToken) => { 
                console.log(idToken);
            });
    }
});

function testCustomLogin(token) {
    firebase.auth().signInWithCustomToken(token)
    .then((signInToken) => {
        console.log("Login OK");
        console.log("signInToken", signInToken);
        signInToken.user.getIdToken()
        .then((usertoken) => {
            let data = {
                token: usertoken
            };
            fetch("/logincookiesession", {
                method: "POST", 
                body: JSON.stringify(data)
            }).then((res) => {
                console.log("Request complete! response:", res);
                console.log("firebase signout");
                auth.signOut()
                    .then(()=> {
                        console.log("redirecting ....");
                        window.location.assign('/');
                        return;
                    })
                    .catch(() => {
                        console.log("error during firebase.signOut");
                    });
                
            });
        });
    })
    .catch(function(error) {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        console.log(errorCode, errorMessage);
    });      
}

Backend code

app.post('/logincookiesession', (req, res) => {
    let token = req.body.token;

    // Set session expiration to 5 days.
    const expiresIn = 60 * 60 * 24 * 5 * 1000;
    // Create the session cookie. This will also verify the ID token in the process.
    // The session cookie will have the same claims as the ID token.
    // To only allow session cookie setting on recent sign-in, auth_time in ID token
    // can be checked to ensure user was recently signed in before creating a session cookie.
    admin.auth().createSessionCookie(token, {expiresIn})
    .then((sessionCookie) => {
        // Set cookie policy for session cookie.
        const options = {maxAge: expiresIn, httpOnly: true, secure: true};
        res.cookie('session', sessionCookie, options);
        res.end(JSON.stringify({status: 'success'}));
    })
    .catch((error) => {
        res.status(401).send('UNAUTHORIZED REQUEST!' + JSON.stringify(error));
    });
});

app.get('/logintest', (req, res) => {
    let userId = 'jcm@email.com';
    let additionalClaims = {
        premiumAccount: true
    };

    admin.auth().createCustomToken(userId, additionalClaims)
    .then(function(customToken) {
        res.send(customToken);
    })
    .catch(function(error) {
        console.log('Error creating custom token:', error);
    });
});

so basically what I do is

  1. execute firebase emulators:start
  2. manually execute this on my browser http://localhost:5000/logintest , this gives me a token printed in the browser
  3. Then in another page, where I have the login form, I open the javascript console of the browser and I execute my javascript function testCustomLogin and I pass as a parameter the token from step 2.

in the network traffic I see that the call to /logincookiesession return this:

UNAUTHORIZED REQUEST!{"code":"auth/invalid-id-token","message":"The provided ID token is not a valid Firebase ID token."}

I am totally lost.

I can see in the firebase console, in the Authentication section that user jcm@email.com is created and signed-in, but I cannot create the session-cookie.

Please,I need some advice here.


Solution

  • The route for creating the cookie session had an error.

    It should start like this.

    app.post('/logincookiesession', (req, res) => {
        let params = JSON.parse(req.body);
        let token = params.token;
    

    And the code I used was from a manual, OMG. I hope this helps someone too.