jonthornham
jonthornham

Reputation: 3335

Sending Custom Tokens Back To Client From Firebase Admin

I am working with the Firebase Admin SDK for Nodejs so that I can mint custom tokens for authentication in iOS devices. In the Nodejs docs it states that you send the token back to the client after it is created.

let uid = 'some-uid';

admin.auth().createCustomToken(uid)
  .then(function(customToken) {
    // Send token back to client
  })
  .catch(function(error) {
    console.log('Error creating custom token:', error);
  });

My question is the most efficient way to do this. I've been thinking about creating Could Function to send it back in a response body but I feel like I may be over thinking it. Is this the recommended method or is there a simpler way I am missing?

Upvotes: 0

Views: 664

Answers (2)

RameshD
RameshD

Reputation: 962

Here is the working code from my application (cloud function) that is as simple as copy paste for your reference.

exports.getCustomToken = functions.https.onRequest(async (req, res) => {
    return cors(req, res, async () => {
        try {
                const token = await createCustomToken(req.body.uid);
                return res.json(token);
        
        } catch (error) {
            res.status(500).json({ message: 'Something went wrong' });
        }
    });
});

async function createCustomToken(userUid, role = '') {

       let createdCustomToken = '';

        console.log('Ceating a custom token for user uid', userUid);
        await firebaseAdmin.auth().createCustomToken(userUid)
            .then(function (customToken) {
                // Send token back to client
                console.log('customToken is ', customToken)
                createdCustomToken = customToken;
            })
            .catch(function (error) {
                console.log('Error creating custom token:', error);
            });
    
         return createdCustomToken;
}

Upvotes: 1

Doug Stevenson
Doug Stevenson

Reputation: 317322

I wouldn't worry too much about efficiency at this point. The token is small and is quick to generate. The first thing to do is just make it work. Use Cloud Functions if you prefer, but the Admin SDK will work on any modern nodejs backend.

Upvotes: 1

Related Questions