简体   繁体   English

在angularjs应用程序中注销后,如何通过浏览器后退按钮禁止用户访问上一页?

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

I have an angularjs web application. 我有一个angularjs Web应用程序。 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. 请提出建议。

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. 使用$stateChangeStart ,此方法在状态更改时调用,查找令牌,如果找不到令牌,则将用户重定向到登录。
  2. use resolve : resolve will get call before routing happens for the respective state, so inside resolve use resolve :resolve将在相应状态的路由发生之前获得呼叫,因此在内部resolve

Method1: 方法1:

$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: 方法2:

$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 
  }
})

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. 在定义ui.router的状态的地方,可以添加用户定义的数据。 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;
}]);

In this mdn article there's explained how to manipulate the browser history: 在此mdn文章中,介绍了如何处理浏览器历史记录:

https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history#Adding_and_modifying_history_entries https://developer.mozilla.org/zh-CN/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. 在我的一个较旧的项目中,我使用它来创建“至上一页”按钮。

A combination of prevent default and window.history.forward() solved the problem. prevent default和window.history.forward()的组合解决了该问题。

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

The idea is event.preventDefault() removes the history stack. 这个想法是event.preventDefault()删除历史记录堆栈。 So if we have gone from page1 -> page2 -> page3, the preventDefault works only as long as reaching the home page. 因此,如果我们从第1页->第2页->第3页开始,则preventDefault仅在到达主页后才起作用。 forward() is needed to keep redirecting to the same page. 需要forward()来保持重定向到同一页面。

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;
            }
        }
    }
);

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. 假设当用户登录到您的应用程序时,系统会生成一个auth-token标记,其中包含表明该用户已通过身份验证的数据。 So since any controller it's executed on page render you just need to put a litle validation for your auth-token. 因此,由于任何控制器都在页面呈现器上执行,因此您只需要为您的auth令牌放置一个小验证即可。 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) 用户转到login.html并输入其凭据(用户/密码)
  2. The system validates the credentials and generate an auth-token 系统验证凭证并生成一个身份验证令牌
  3. The system save the token with lets say: tokenManager.save(); 系统使用以下命令保存令牌:tokenManager.save();
  4. The user is now in welcome.html page. 用户现在位于welcome.html页面中。
  5. The user logout from the system. 用户从系统注销。
  6. The system delete the auth-token, let's say: tokenManager.clean(); 系统删除auth令牌,比如说: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. 系统尝试进入welcome.html页面,但是它自己的控制器已经过验证。
  9. The user is redirected to login.html 用户被重定向到login.html
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");
                        }
                    })
                })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在angular2中注销后,如何通过浏览器后退按钮禁止用户访问上一页? - How to disable users from accessing previous page by browser back button after logout in angular2? 注销后禁用 spring mvc 应用程序中的浏览器后退按钮 - Disable browser back button in spring mvc application after logout 注销后禁用浏览器的“返回”按钮? - Disable browser 'Back' button after logout? 单击PHP中的注销按钮后如何禁用浏览器后退按钮功能 - How to Disable Browser Back Button functionality after click on Logout Button in PHP 禁用一页应用程序的浏览器后退按钮 - Disable browser back button for one page application 注销后将禁用“返回”按钮 - Back button to be disable after logout 如何禁用AngularJS中的浏览器后退按钮? - How to disable browser back button in AngularJS? 如何仅在 mvc3.net 中注销后禁用浏览器后退按钮 - How Disable Browser Back Button only after Logout in mvc3.net 如何为浏览器后退按钮指定上一页 - How to specify the previous page for browser back button 当用户从页面注销时……如果用户单击浏览器后退按钮,它将重定向到先前的URL并显示HTML页面几秒钟 - When user logout from page … if user click browser back button ,which will redirect to previous URL and display HTML page for few seconds
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM