johnbraum
johnbraum

Reputation: 296

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!

Upvotes: 7

Views: 2353

Answers (2)

JoeWemyss
JoeWemyss

Reputation: 607

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')});
    }

Upvotes: 10

Richard Ansell
Richard Ansell

Reputation: 926

I believe you should be able to do this, by using Firebase to authorise the user and then allow read access to a link securely stored for authenticated users only. This could then link to the database, if this is what you mean. I'd assume you may have already started here, but this is where to start Understand Firebase Realtime Database Rules

Upvotes: 0

Related Questions