AngularJS:使用angularjs保护路由取决于用户是否被授权? [英] AngularJS: Protecting routes with angularjs depending if the user is authorized?

查看:68
本文介绍了AngularJS:使用angularjs保护路由取决于用户是否被授权?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用正在开发的AngularJS应用程序,一切都很好,但是我需要一种保护路由的方法,这样,如果未登录,则不允许用户使用该路由. .我也了解在服务端进行保护的重要性,并且我将对此予以照顾.

I have just started out working with an AngularJS app I'm developing, everything is going well but I need a way of protecting routes so that a user wouldn't be allowed to go to that route if not logged in. I understand the importance of protecting on the service side also and I will be taking care of this.

我发现了多种保护客户端的方法,其中一种似乎使用了以下方法

I have found a number of ways of protecting the client, one seems to use the following

$scope.$watch(
    function() {
        return $location.path();
    },
    function(newValue, oldValue) {
        if ($scope.loggedIn == false && newValue != '/login') {
            $location.path('/login');
        }
    }
);

我需要把它放在app.js中的.run中吗?

where do I need to put this, in the .run in the app.js?

我发现的另一种方法是使用指令并使用on-routechagestart

And the other way I have found is using a directive and using an on - routechagestart

信息在此处 http://blog.brunoscopelliti.com/deal-with-users-authentication-in-an-angularjs-web-app

我真的会对任何人对推荐方法的帮助和反馈感兴趣.

I would really be interested in anyones help and feedback on the recommended way.

推荐答案

在这里使用解决方法应该可以为您提供帮助:(未经测试的代码)

Using resolves should help you out here: (code not tested)

angular.module('app' []).config(function($routeProvider){
    $routeProvider
        .when('/needsauthorisation', {
            //config for controller and template
            resolve : {
                //This function is injected with the AuthService where you'll put your authentication logic
                'auth' : function(AuthService){
                    return AuthService.authenticate();
                }
            }
        });
}).run(function($rootScope, $location){
    //If the route change failed due to authentication error, redirect them out
    $rootScope.$on('$routeChangeError', function(event, current, previous, rejection){
        if(rejection === 'Not Authenticated'){
            $location.path('/');
        }
    })
}).factory('AuthService', function($q){
    return {
        authenticate : function(){
            //Authentication logic here
            if(isAuthenticated){
                //If authenticated, return anything you want, probably a user object
                return true;
            } else {
                //Else send a rejection
                return $q.reject('Not Authenticated');
            }
        }
    }
});

这篇关于AngularJS:使用angularjs保护路由取决于用户是否被授权?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆