Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if user is authenticated in AngularJS router?

I have an application set up with the Mean.js yeoman generator. It uses PassportJS to setup local-authentication. This all works great and I understand how to check if a user is logged in from the ExpressJS routes file.
The problem is that most of my page routing is done in the angular routes. I know how to check authentication in the controller with the the following code.

// Projects controller
angular.module('projects').controller('ProjectsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Projects',
    function($scope, $stateParams, $location, Authentication, Projects) {
        $scope.authentication = Authentication;

But how do I check authentication in the routes. For example in this routes files how would I only allow authenticated users to access the tools html file and redirect users that arent logged in back to the home page:

'use strict';

//Setting up route
angular.module('analysis').config(['$stateProvider',
    function($stateProvider) {
        // Projects state routing
        $stateProvider.
        state('imageAnalysis', {
            url: '/analysis',
            templateUrl: 'modules/analysis/views/tools.client.view.html'
        });
    }
]);

I know there are similar posts out there but I had trouble understanding many of them. Thanks, I really appreciate any help. I am new to the stackoverflow community and still learning community standards.

like image 697
Daniel Kobe Avatar asked Dec 15 '25 12:12

Daniel Kobe


1 Answers

At a high level, there are two approaches:

  • Use your view routing layer (e.g. UI Router) to catch “unauthenticated” state

  • Use HTTP interceptors to look for requests that have a 401 Unauthorized status, indicating that the user must login (or that their current session has expired)

In practice you’ll probably use a combination of both.

Speaking to the UI Router, there a two of doing this: resolves or events.

Resolves: The UI Router provides a nice feature called resolves, which allows you to provide a promise that must be resolved before the view is rendered. You could create a promise which resolves your user state.

Events: The UI Router provides a $stateChangeStart event, you can observe this event and prevent it if the user is not logged in. You would then send the user to login page. This is a bit more stateful (you have to remember where the user wanted to go in the first place, so that you can redirect after login).

I chose the event approach for my work on the Stormpath Angular SDK because it gives me the flexibility to define authorization on top of authentication.

like image 53
robertjd Avatar answered Dec 17 '25 01:12

robertjd