Angular re-route to login page on user session expiration when user redirects to another route

Goal:

Whenever the user redirects to another route via the Angular route provider, check the server if the user is still logged in by creating an MVC controller/action to verify the user session. If the user's session has expired, redirect the user to the login page.

 

Environment:

- .Net MVC Core 1.0

- Angular SPA

 

Solution:

 

Create an MVC controller (HomeController) to verify if the user's session has expired. In this scenario, we decided to check the .Net authentication cookie we create as part of the user's session.

 

        [Route("usercookieexists")]

        [HttpGet]

        public bool UserCookieExists()

        {

            return HttpContext.Request.Cookies[".User"] != null;

        }

 

Now add the run to the Angular configuration:

 

(function() {

    angular.module('module', ['core'])

        .config([

            '$httpProvider', '$stateProvider', 

            function($httpProvider, $stateProvider) {

            }

        ])

        .run([

            '$state', '$rootScope', "$http", "coreFactory", function($state, $rootScope, $http, core) {

                $rootScope.$on('$stateChangeStart', function(event, current, previous) {

                   

                    //see if the user's cookie still exists, if not it has expired and redirect the user to log in again

                    $http.get("/home/usercookieexists")

                        .success(function(result) {

                            if (!result) {

                                $rootScope.user = {};

                                core.confirm.show("Session Expired", "Your session has expired. Please log in again",

                                    function() {

                                        location.replace($rootScope.baseUrl + "/Account/Login");

                                    },

                                    null, true, "OK", false, null

                                );

                            }

                        });

 

                });

            }

        ]);

})();

 

The coreFactory is simply an Angular factory for displaying a modal dialog in stead of a JS alert popup. You can ignore it a simply use a regular JS alert.

 

Print | posted @ Thursday, August 11, 2016 9:56 AM

Comments on this entry:

Gravatar # re: Angular re-route to login page on user session expiration when user redirects to another route
by Brad Fonnoley at 8/25/2016 6:29 AM

Now, this really helps me to understand the whole process. - Morgan Exteriors
Post A Comment
Title:
Name:
Email:
Comment:
Verification: