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) {
                            }).catch(function (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

                return deferred.promise;

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

Silviu Stroe

Silviu is a full stack developer and entrepreneur. He is the founder of one of the first VPN services in Romania, RoTunneling and is part of Yahoo - Wall of Fame. He also loves bleeding edge technologies and new challenges.

No Comments

You can leave the first : )

Leave a Reply

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