How to disable users from accessing previous page by browser back button after logout in angularjs application?

17.7k Views Asked by At

I have an angularjs web application. I am trying not to allow users to go to previous page using browser back button after logout. I wish to show users a messge like "Please login to continue". I am unable to get any ideas. Please suggest.

7

There are 7 best solutions below

1
SiriK On BEST ANSWER
app.config(["$routeProvider", function($routeProvider) {
            return $routeProvider.when("/", {
                redirectTo: "/login"
            }).when("/dashboard", {
                templateUrl: "views/dashboard.html"
            }).when("/login", {
                templateUrl: "views/login.html"
            }).when("/pages/openAcc", {
                templateUrl: "views/pages/openAcc.html"
            }).when("/pages/docUpload", {
                templateUrl: "views/pages/docUpload.html"
            }).when("/pages/listview", {
                templateUrl: "views/pages/listview.html"
            }).otherwise({
                redirectTo: "/404"
            })
        }])    .run(function($rootScope, $location) {
                    $rootScope.$on("$routeChangeStart", function (event, next, current) {
                        if (!(next.templateUrl == "views/login.html")) {
                            $location.path("/login");
                        }
                    })
                })
2
Gopinath Shiva On

You can disable access to previous page using 2 ways:

  1. use $stateChangeStart, this method invoke whenever the state is changed, look for token, if token is not found, redirect user to login.
  2. use resolve: resolve will get call before routing happens for the respective state, so inside resolve

Method1:

$rootScope.$on('$stateChangeStart', 
function(event, toState, toParams, fromState, fromParams){         
    // check if user is navigating to anypage other than login, if so check for token, if token is not present redirect to login page        
});

Method2:

$stateProvider.state("dashboard", {      
  resolve: { 
  // check if user is navigating to anypage other than login, if so check for token, if token is not present redirect to login page by using defer 
  }
})
0
Raphael Müller On

You can implement something similar to have access control over different content. Please be aware that you also have to secure your backend.

Where you define your states for the ui.router, you can add user defined data. For example:

angular.module("app", ['ui.router']).config(['$stateProvider', function($stateProvider){
    $stateProvider.state('yourSecureState', {
                    url: '/secure-state',
                    templateUrl: '/app/views/secure.html',
                    controller: 'SecureStateController',
                    data: {
                        accessLevel: "secured-feature",
                        title: 'Secured State'
                    }
                });
}]);

With this additional information, you can check in your authentication service if the required access level is available:

angular.module('app').factory('AuthService', ['$rootScope', function($rootScope){
    $rootScope.$on('$stateChangeStart', function (event, nextState) {
            if (nextState.data && nextState.data.accessLevel && !service.isAuthorized(nextState.data.accessLevel)) {
                event.preventDefault();
                alert("Not Authorized");
            }
        });

    var service = {
       isAuthorized: function(accessLevel) {
            //your code here:
       }
    };

    return service;
}]);
0
machinateur On

In this mdn article there's explained how to manipulate the browser history:

https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history#Adding_and_modifying_history_entries

On one of my older projects I used this to create a "to previous page" button.

0
codebear22 On

Let's say when the user is logged in to your app, the system generates an auth-token wich contains data that suggest that the user is authenticated. So since any controller it's executed on page render you just need to put a litle validation for your auth-token. If this token is not there, then redirect to login page. I think, you don't need to block any back button.

// First lines inside your controller.
if (!$tokenManager.getToken()) { // Get token.
    $location.path('/login');
}

The flow would be:

  1. The user go to login.html and put its credentials (user/password)
  2. The system validates the credentials and generate an auth-token
  3. The system save the token with lets say: tokenManager.save();
  4. The user is now in welcome.html page.
  5. The user logout from the system.
  6. The system delete the auth-token, let's say: tokenManager.clean();
  7. The user press the back button browser button.
  8. The system try to enter to welcome.html page but it's own controller has the validation.
  9. The user is redirected to login.html
1
Vikram On

A combination of prevent default and window.history.forward() solved the problem.

$rootScope.$on('$stateChangeStart', 
   function(event, toState, toParams, fromState, fromParams){ 
      event.preventDefault();
      window.history.forward();
});

The idea is event.preventDefault() removes the history stack. So if we have gone from page1 -> page2 -> page3, the preventDefault works only as long as reaching the home page. forward() is needed to keep redirecting to the same page.

0
Viorel Mateianu On

The following code disables the browser Back button all over your app:

var allowNav = false;
var checkNav = false;

$rootScope.$on(
    '$stateChangeSuccess',
    function (event, toState, toStateParams, fromState, fromStateParams) {
        allowNav = checkNav;
        checkNav = true;
    }
);

$rootScope.$on(
    '$locationChangeStart',
    function (event, next, current) {
        // Prevent the browser default action (Going back)
        if (checkNav) {
            if (!allowNav) {
                event.preventDefault();
            } else {
                allowNav = false;
            }
        }
    }
);