简体   繁体   中英

Angular.js, how to check authentication service in controllers

In angular.js, on all controllers that require authentication I am doing the following:

function controller($state, $rootScope, $scope, oAuthService) {
    //oAuthService is a custom service
    if(!oAuthService.isAuthorized()) {
         $state.go('401');
    }
    ...
}

The problem is two fold. First, I don't like that I have to copy and paste these 3 lines into the top of every controller that requires auth. Second, if you transition to another controller authentication is not checked (only check when the page is hard refreshed) . What is the best way of doing this?

add below lines of code in your root controller..

    $rootScope.$on("$stateChangeStart", function (event, oAuthService) {
        if(!oAuthService.isAuthorized()) {
                   $state.go('401');
                   event.preventDefault();
        }
    }

EDIT

to answer your comment.

you should set some boolean property on each state indicating whether auth is needed.

   .state('home', {
        url: '/home',
        templateUrl: 'partial-home.html',
        isSecured: true
    })

and then

    $rootScope.$on("$stateChangeStart", function (event, toState) {
        if(!oAuthService.isAuthorized() && toState.isSecured && toState.name != '401') {
                   $state.go('401');
                   event.preventDefault();
        }
    }

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