How to send Firebase user auth token with every request in AngularJS

Hello, guys!

If you want to build an AngularJS app based of Firebase, probably at a certain time you want to verify if the logged user it’s the same one that makes requests to your backend server in order to serve specific data securely.
For this to happen, we must write a service that will return a promise which contains the logged user’s token if the user is authenticated or else a error.


 .factory('User', function ($q) {

        return {
            authToken: function () {
                return $q(function (resolve, reject) {
                    firebase.auth().onAuthStateChanged(function (user) {
                        if (user) {
                            user.getToken().then(function (data) {
                                resolve(data);
                            }).catch(function (err) {
                                reject(err);
                            });
                        }
                    });
                })
            }
     
        }

    })

Then, we need a http request interceptor that will wait for the token promise defined above and will inject it in every http header request.

angular.module('YourApp').config(function ($httpProvider) {
  
    $httpProvider.interceptors.push(function (User, $q) {
        return {
            request: function (req) {
                var deferred = $q.defer();
                // Set the `Authorization` header for every outgoing HTTP request
                User.authToken().then(function (data) {
                    req.headers.Authorization = data; //set the Auth token
                    deferred.resolve(req);
                });

                return deferred.promise;
            }
        };
    })
});

Now, all you need is to verify the token on your backend.

Silviu Stroe
I'm Silviu and I run Brainic, a mobile-focused software agency. I'm also a member of Nokia and Yahoo wall of fame. My interests are in low-code/no-code development and bleeding-edge technologies.

Leave a Reply

Your email address will not be published. Required fields are marked *