问题
I'm using Angularjs with ui-router and JWT(which is a tool for token based authentication) and want to implement authentication.
Say i want to restrict access to all my pages except three: "/home", "/about" and "/login". How can I achieve this effect?
回答1:
it's working ! enjoy :)
var scotchApp = angular.module('scotchApp', ['ngCookies','ngRoute','ui.bootstrap']);
scotchApp.run(['$rootScope', '$location', 'Auth', function($rootScope, $location, Auth) {
$rootScope.$on('$routeChangeStart', function(event, current) {
$rootScope.pageTitle = current.$$route.title;
if (!Auth.isLoggedIn() && current.$$route.withLogin || Auth.isLoggedIn() && current.$$route.withoutLogin) {
event.preventDefault();
$location.path('/');
}
});
}]);
scotchApp.config(function($routeProvider) {
$routeProvider
// route for the home page
.when('/list', {
templateUrl: 'pages/list.html',
controller: 'mainController',
title: 'User List',
withLogin: true,
})
.when('/register', {
templateUrl: 'pages/register.html',
controller: 'mainController',
title: 'Register',
withoutLogin: true,
});
});
回答2:
bellow I'll explain for you how to protect access using angularjs Philosophy:
1- we supposed that you have factory named verifyLogin
this factory used to verify if the user connect or not (inside this factory function named isAuth
)
2 -file config contains the bellow code:
$stateProvider
.state('docApp.doc_components_profiles', {
needLogin: true,
url : '/admin/page1',
views: {
'content@docApp': {
templateUrl: 'app/admin/pages/profiles.html',
controller : 'AdminController as vm'
}
}
});
here you see that we write attribute named needLogin
and we affect to this attribute value = true,in order to access to this path (admin pages) the user must be authenticated.
3 -now you can write as bellow to verify the path each time the user navigate from one to another
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams){
if(toState.needLogin){
if(verifyLogin.isAuth== false)
{
console.log("Ypou must connect before you access to this url!!");
$location.path('/login');
}
}
}
来源:https://stackoverflow.com/questions/28944474/angularjs-restrict-access-to-all-pages-except-few