AngularJs SPA注销

时间:2016-03-11 06:08:11

标签: javascript angularjs authentication single-page-application logout

我在AngularJs logout action发布了更复杂的问题。但我还有另一个方面要看,我认为这应该是分开的问题。

我有Angualr SPA认证。使用承载JWT令牌实现身份验证。我使用ng-route制作不同的观点。让我们想象一下,一个视图(使用/protected路由,protecetedControllerprotectedDataService)包含受保护资源,另一个视图(使用/unprotected路由,unprotecetedControllerunprotectedDataService)包含未受保护的资源。控制器示例代码:

(function () {
    'use strict';

    angular
        .module('protectedCtrl',[])
        .controller('protectedController', ['$location','protectedDataService', function ($location, protectedDataService) {
            var vm = this;
            vm.title = 'protectedController';
            protectedDataService.getData().then(function (res) {
                vm.values = res.data;
            }, function (err) {
                console.log(err);
            });
        }]);
})();

未受保护的控制器:

(function () {
    'use strict';

    angular
        .module('unprotectedCtrl',[])
        .controller('unprotectedController', ['$location','unprotectedDataService', function ($location, unprotectedDataService) {
            var vm = this;
            vm.title = 'unprotectedController';
            unprotectedDataService.getData().then(function (res) {
                vm.values = res.data;
            }, function (err) {
                console.log(err);
            });
        }]);
})();

如果未登录用户转到受保护资源(/protected路径),他将被重定向到登录页面。但让我们想象一下,登录用户按下注销按钮(现在我只是从浏览器本地删除我的令牌信息并重新加载页面)。如果用户在/protected页面上,则应将其重定向到登录页面。如果他在/unprotected页面,则不会发生任何事情。我该如何实现呢?如何确定ng-view中哪个页面处于活动状态(需要auth或不需要auth)并决定重定向?

1 个答案:

答案 0 :(得分:1)

您可以使用$routeChangeStart事件来捕获路由更改和帮助程序函数,以决定是否重定向到登录页面。

在角度应用的run块中,为不需要身份验证的路由定义变量,并检查用户前往的路由是否在此列表中。

angular
  .module('awesomeApp')
  .run(function (/* inject dependencies */) {
    // other code

    // Define a list of routes that follow a specific rule. This example
    // can be extended to provide access based on user permissions by
    // defining other variables that will list routes that require the
    // user to have specific permissions to access those routes.
    var routesThatDoNotRequireAuthentication = ['/unprotected'];

    // Check if current location is contained in the list of given routes.
    // Note: the check here can be made using different criteria. For
    // this example I check whether the route contains one of the
    // available routes, but you can check for starting position, or other criteria.
    function rootIsPresent ( route, availableRoutes ) {
      var routeFound = false;
      for ( var i = 0, l = availableRoutes.length; i < l; i++ ) {
        routeFound = routeFound || route.indexOf(availableRoutes[i]) > -1;
      }
      return routeFound;
    }

    // And now, when the $routeChangeStart event is fired, check whether
    // its safe to let the user change the route.
    $rootScope.$on('$routeChangeStart', function () {
      // Get the authentication status of a user
      var isAuthenticated = authenticationService.isAuthenticated();
      var newRoute = $location.url();

      // If the route requires authentication and the user is not 
      // authenticated, then redirect to login page.
      if ( !rootIsPresent(newRoute, routesThatDoNotRequireAuthentication) && !isAuthenticated ) {
        $location.path('/login');
      }
    });
});

更新

似乎我误解了这个问题,并认为你的所有路线都以/protected/unprotected为前缀(如果你考虑一下,这真的不是那么聪明)大多数情况)。

在这种情况下,您可以在$routeProvider中定义路径时设置其他属性:

$routeProvider
  .when('/awesomePath', {
    templateUrl: 'awesome-template.html',
    controller: 'AwesomeController',
    controllerAs: 'vm',
    requireAuth: true  // add the property that defines a route as protected or unprotected
  })

现在,在你的$routeChangeStart处理函数中,检查路由用户是否会受到保护:

$rootScope.$on('$routeChangeStart', function () {
      // Get the authentication status of a user
      var isAuthenticated = authenticationService.isAuthenticated();
      var newRoute = $location.url();

      // In a controller, $route object has a 'current' property that
      // holds route defined route properties, but here the 'current'
      // property is null, so we need to get the $route object we 
      // need by using the $location.url()
      if ( $route.routes[$location.url()].requireAuth && !isAuthenticated ) {
        $location.path('/login');
      }
    });

因此,您无需在任何地方对路线进行硬编码。