3

我用生成器创建了一个新路由“Rooms”,并在管理路由上建模了我的 $stateProvider

.state('admin', {
    url: '/admin',
    templateUrl: 'app/admin/admin.html',
    controller: 'AdminController',
    controllerAs: 'admin',
    authenticate: 'admin'
  });

VS

$stateProvider
  .state('rooms', {
    url: '/rooms',
    templateUrl: 'app/rooms/rooms.html',
    controller: 'RoomsCtrl',
    controllerAs: 'rooms',
    authenticate: 'admin'
  });

但我的路线仍然出现没有身份验证!

我想我错过了一些使它安全的东西,尽管我无法理解是什么!

任何人都可以帮忙吗?

谢谢

4

2 回答 2

1

你的控制器应该是这样的:

     angular.module('auth8App').controller('RoomsCtrl', function ($scope,Auth,$location) {

               //check if the user is logged-in
                Auth.isLoggedInAsync(function(loggedIn) {
                        if (!loggedIn) {    
                       //if the user is not logged  Redirect to login
                          event.preventDefault();
                          $location.path('/login');
                        }
                      });
                    $scope.message = 'Hello';
                });
于 2015-12-11T09:36:06.960 回答
0

检查您是否在 app.js 中定义并调用了拦截器服务工厂,如下所示:

    .config(function ($stateProvider, $urlRouterProvider, $locationProvider, $httpProvider) {
    $urlRouterProvider
      .otherwise('/');

    $locationProvider.html5Mode(true);
    $httpProvider.interceptors.push('authInterceptor');
  })

  .factory('authInterceptor', function ($rootScope, $q, $cookieStore, $location) {
    return {
      // Add authorization token to headers
      request: function (config) {
        config.headers = config.headers || {};
        if ($cookieStore.get('token')) {
          config.headers.Authorization = 'Bearer ' + $cookieStore.get('token');
        }
        return config;
      },

      // Intercept 401s and redirect you to login
      responseError: function(response) {
        if(response.status === 401) {
          $location.path('/login');
          // remove any stale tokens
          $cookieStore.remove('token');
          return $q.reject(response);
        }
        else {
          return $q.reject(response);
        }
      }
    };
  })

  .run(function ($rootScope, $location, Auth) {
    // Redirect to login if route requires auth and you're not logged in
    $rootScope.$on('$stateChangeStart', function (event, next) {
      Auth.isLoggedInAsync(function(loggedIn) {
        if (next.authenticate && !loggedIn) {
          event.preventDefault();
          $location.path('/login');
        }
      });
    });
  });
于 2015-12-11T08:09:16.223 回答