首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >AngularJs SPA注销

AngularJs SPA注销
EN

Stack Overflow用户
提问于 2016-03-11 06:08:11
回答 1查看 782关注 0票数 1

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

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

代码语言:javascript
运行
复制
(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);
            });
        }]);
})();

无保护控制器:

代码语言:javascript
运行
复制
(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中是活动的(需要或不需要)并做出重定向的决定?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-03-11 09:26:35

您可以使用$routeChangeStart事件捕捉路由和助手函数的更改,以决定是否重定向到登录页面。

在您的角应用程序的run块中,为不需要身份验证的路由定义一个变量,并定义一个函数来检查用户要去的路由是否在此列表中。

代码语言:javascript
运行
复制
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中定义路由时设置附加属性。

代码语言:javascript
运行
复制
$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处理程序函数中,检查路由用户是否将受到保护:

代码语言:javascript
运行
复制
$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');
      }
    });

因此,您不需要硬编码您的路线在任何地方。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35933413

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档