我会在 routeProvider 中进行检查。这必须对每条需要身份验证的路由进行。您甚至可以编写一个单独的方法并将其粘贴到每条路线上以避免重复。
$routeProvider
.when('/profile', {
templateUrl: 'views/profile.html',
controller: 'ProfileCtrl',
resolve: {
validate: function($q, $location) {
// Either you could maintain an array of hashes on client side
// a user do not have access to without login
// Or hit the backend url to check it more securely
var validateAccess = $q.defer();
var isAllowed = ['profile', 'index', 'dashboard'].indexOf($location.hash()) !== -1;
if (!isAllowed) {
$location.path('/login');
}
validateAccess.resolve();
return validateAccess.promise;
}
}
})
.otherwise({
redirectTo: '/'
});