AngularJS路由与授权过程 [英] AngularJS Routing with Authorization Process

查看:193
本文介绍了AngularJS路由与授权过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现基本的身份验证AngularJS路由。我有一个返回一诺法授权的模式。我希望路由等到授权函数返回true或false继续,一旦完成就应该恢复路径,或将用户重定向到登录页面。

我觉得基本上我需要停下来路由,调用该方法,然后恢复或重定向登录。下面是code我有这么远,但我不知道如何实现暂停/恢复。任何想法?

 返回angular.module('D',['ngCookies','ngRoute'])
    的.config(['$ routeProvider','$ locationProvider','$ httpProvider',
        功能($ routeProvider,$ locationProvider,$ httpProvider){            $ routeProvider.when('/',
            {
                templateUrl:意见/ home.html做为',
                控制器:'HomeCtrl
            });
            $ routeProvider.when('/登录,
            {
                templateUrl:意见/ login.html的,
                控制器:'LoginCtrl
            });            $ routeProvider.otherwise({redirectTo:'/ 404'});
            $ locationProvider.html5Mode(真);            //通过重定向到登录页面处理未授权的请求
            $ httpProvider.responseInterceptors.push(
                ['$的位置,$ Q',函数($位置,$ Q){
                    函数成功(响应){
                        返回响应;
                    }                    功能错误(响应){
                        如果(response.status === 401){
                            $ location.path('/登录');
                            返回$ q.reject(响应);
                        }
                        其他{
                            返回$ q.reject(响应);
                        }
                    }                    复位功能(承诺){
                        返回promise.then(成功,错误);
                    }
                }]);        }])
    .RUN(['$ rootScope','$的位置,验证,函数($ rootScope,$位置,验证){        $ rootScope。在$($ routeChangeStart功能(事件,接下来,电流){
            $ rootScope.error = NULL;
            Auth.authorize()。然后(函数(){
                $ location.path('/');
            },功能(){
                $ location.path('/登录');
            });
        });    }]);


解决方案

您的解决方案是非常相似的原型,我写了一段时间回来。

我们的想法是,只要你触摸的服务器,并得到一个身份验证错误,模态窗口弹出,询问一个登录的没有的更改URL(你让其更改为新的URL呆在那里)。

我的实现也是基于一个拦截器检查401它有$ rootScope的依赖,并设置属性needsLogin为true。页面模板有登录模式窗口时可见 needsLogin ===真正并隐藏了NG-观点(这是重要的,因为新的路径已被加载但却忽略其数据)。最后,在全成登录,登录控制器是否 $ route.reload(),然后设置 $ rootScope.needsLogin = FALSE

小片段:

 < D​​IV ID =主角色=主NG-秀=needsLogin ===假>
    < D​​IV NG-视图>< / DIV>
< / DIV>< D​​IV NG秀=needsLogin ===真正的NG-包括='意见/ login.html的'级=叠加>< / DIV>

登录控制可以是这样的:

 函数LoginCtrl($范围,$ rootScope,$路径,$ HTTP){    $ scope.login =功能(){
        $ http.post(/ *不知做你的登录* /)
            .success(函数(){
                VAR DEREGISTER = $ rootScope。在$('$ routeChangeSuccess',函数(){
                    //路线后隐藏登录/显示NG-观点已被重新加载
                    $ rootScope.needsLogin = FALSE;
                    注销();
                });
                $ route.reload();
            })
            .error(函数(){
                / *处理错误* /
            });
    };
}

$ route.reload()不是一个完整的页面刷新,它只是重新初始化路线(控制器/视图等)。我们希望,这是之前拒绝了呼叫,将再次运行和页面将被罚款。

I'm trying to implement basic authentication routing in AngularJS. I have a model that has a authorize method that returns a promise. I want the routing to wait until that authorize function has returned true or false to continue, once that has completed it should resume the path or redirect the user to the login page.

I think essentially i need to stop routing, call that method and then resume or redirect to login. Below is the code I have so far but i'm not sure how to accomplish the pause/resume. Any ideas?

return angular.module('d', ['ngCookies', 'ngRoute'])
    .config(['$routeProvider', '$locationProvider', '$httpProvider', 
        function ($routeProvider, $locationProvider, $httpProvider) {

            $routeProvider.when('/',
            {
                templateUrl: 'views/home.html',
                controller: 'HomeCtrl'
            });
            $routeProvider.when('/login',
            {
                templateUrl: 'views/login.html',
                controller: 'LoginCtrl'
            });

            $routeProvider.otherwise({ redirectTo: '/404' });
            $locationProvider.html5Mode(true);

            // handle unauthorized requests by redirecting to login page
            $httpProvider.responseInterceptors.push(
                ['$location', '$q', function ($location, $q) {
                    function success(response) {
                        return response;
                    }

                    function error(response) {
                        if (response.status === 401) {
                            $location.path('/login');
                            return $q.reject(response);
                        }
                        else {
                            return $q.reject(response);
                        }
                    }

                    return function (promise) {
                        return promise.then(success, error);
                    }
                }]);

        }])
    .run(['$rootScope', '$location', 'Auth', function ($rootScope, $location, Auth) {

        $rootScope.$on("$routeChangeStart", function (event, next, current) {
            $rootScope.error = null;
            Auth.authorize().then(function(){
                $location.path('/');
            },function(){
                $location.path('/login');
            });
        });

    }]);

解决方案

Your solution is very similar to a prototype I wrote a while back.

The idea is that whenever you "touch" the server and get an authentication error, a modal window pops-up asking for a login without changing the URL (you let it change to the new URL and stay there).

My implementation was also based on an interceptor checking for 401. It has a dependency on $rootScope and sets a property "needsLogin" to true. The page template has the login modal window visible when needsLogin === true and hides the ng-view (this is important since the new route has been loaded but it misses its data). Finally, upon successfull login, the login controller does the $route.reload() and then sets $rootScope.needsLogin = false.

Small snippets:

<div id="main" role="main" ng-show="needsLogin === false">
    <div ng-view></div>
</div>

<div ng-show="needsLogin === true" ng-include="'views/login.html'" class="overlay"></div>

The login controller can be something like:

function LoginCtrl($scope, $rootScope, $route, $http) {

    $scope.login = function () {
        $http.post( /* Somehow do your login */ )
            .success(function () {
                var deregister = $rootScope.$on('$routeChangeSuccess', function () {
                    // hide login / show ng-view after route has been reloaded
                    $rootScope.needsLogin = false;
                    deregister();
                });
                $route.reload();
            })
            .error(function () {
                /* handle errors */
            });
    };
}

$route.reload() is not a full page refresh, it merely re-initializes the route (controller/view etc). Hopefully, the call that was rejected before will run again and the page will be fine.

这篇关于AngularJS路由与授权过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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