Protecting routes with authentication in an AngularJS app
Posted
by
Chris White
on Stack Overflow
See other posts from Stack Overflow
or by Chris White
Published on 2014-06-08T14:57:36Z
Indexed on
2014/06/08
15:25 UTC
Read the original article
Hit count: 160
Some of my AngularJS routes are to pages which require the user to be authenticated with my API. In those cases, I'd like the user to be redirected to the login page so they can authenticate. For example, if a guest accesses /account/settings
, they should be redirected to the login form.
From brainstorming I came up with listening for the $locationChangeStart
event and if it's a location which requires authentication then redirect the user to the login form. I can do that simple enough in my applications run()
event:
.run(['$rootScope', function($rootScope) {
$rootScope.$on('$locationChangeStart', function(event) {
// Decide if this location required an authenticated user and redirect appropriately
});
}]);
The next step is keeping a list of all my applications routes that require authentication, so I tried adding them as parameters to my $routeProvider
:
$routeProvider.when('/account/settings', {templateUrl: '/partials/account/settings.html', controller: 'AccountSettingCtrl', requiresAuthentication: true});
But I don't see any way to get the requiresAuthentication
key from within the $locationChangeStart
event.
Am I overthinking this? I tried to find a way for Angular to do this natively but couldn't find anything.
© Stack Overflow or respective owner