简体   繁体   中英

How should I invalidate user access tokens in AngularFire/Firebase?

Context

Using instructions for logging out users found here and here .

I am using AngularFire with AngularJS, and authenticating users with the e-mail & password method.

The Problem

Calling $unauth does not invalidate a user's token: Subsequent calls to $authWithPassword return an identical authentication token.

Note: Tokens invalidate correctly after the expiration time set on the server.

The Code

angular
    .module('app')
    // Auth Factory
    .factory("Auth", ["$firebaseAuth", "FIREBASE_URI",
        function($firebaseAuth, FIREBASE_URI) {
            var ref = new Firebase(FIREBASE_URI);
            return $firebaseAuth(ref);
        }
    ])

Controller:

function authenticationCtrl($scope, $state, authService) {
    var authenticationCtrl = this;

    // LOGIN
    var login = function (userObject) {
        authService.loginWithPassword(userObject, function () {
            $state.go('[...]');
        },
        function (errorText) {
            // ERROR
            console.error("Error logging in user:", errorText)
        });
    };

    // LOGOUT
    var logout = function () {
        // Clear locally logged in user
        $scope.authData = null;
        authService.logout();
    };

    // PUBLIC
    return {
        login: login,
        logout: logout
    };
};

angular
    .module('app')
    .controller('authenticationCtrl', authenticationCtrl)

Service:

function authService($state, FIREBASE_URI, Auth) {
    var model = this,
        ref = new Firebase(FIREBASE_URI);

    // LOGIN
    model.loginWithPassword = function(credentials, callBack, errorCallBack) {
        Auth.$authWithPassword(credentials)
            .then(function(authData) {
                model.cachedUser = authData;
                callBack();
            }).catch(function(error) {
                console.error("Authentication failed:", error);
            });
    };

    // LOGOUT
    model.logout = function() {
        Auth.$unauth();
        model.cachedUser = null;
        $state.go('common.login');
    };
};

angular
    .module('app')
    .service('authService', authService)

You cannot manually invalidate a token if you're using Firebase's email & password authentication provider. The only way to do that is to use a Custom Authentication implementation to generate tokens yourself. You can then invalidate a token by revoking the Firebase secret that was used to generate the token.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM