Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Auth + Own Api

is it possible to use only the firebase auth and then create an own api with own database?

So I write an REST API which uses the firebase token to authentificate.

Thanks!

like image 919
johnbraum Avatar asked Feb 09 '17 21:02

johnbraum


1 Answers

It depends on the technology that you will be using for the backend API. There is a Firebase Admin SDK, that is aimed at Java, Python and Node developers, but I think the functionality that you are looking for is only available in the Node SDK (although I believe that there are workarounds for this).

The way this works is that after your user signs in on the client side, they can request a token using firebase.auth().currentUser.getIdToken() which can then be passed to your backend which can then be verified, see the below example for how it could be done using Node and Restify.

    const server = restify.createServer({});
    server.use(validateJwt);

    function validateJwt(req, res, next) {

        if(!req.headers.token){
            //reject
        }
        admin.auth().verifyIdToken(req.headers.token).then(decodedToken=>{
            console.log(`token for user ${decodedToken.sub} valid`);
            admin.auth().getUser(decodedToken.sub).then(user=>{
                console.log(`fetched user ${user.email}`);
                next();
            }).catch(err=>{
                res.send(500, 'the user with the ID does not exist in firebase');
            })
        }).catch(err=>{
            console.log(`token validation failed: ${err}`); 
            res.send(401, 'authentication failed')});
    }
like image 148
JoeWemyss Avatar answered Sep 29 '22 15:09

JoeWemyss