如何使用 ui-router 检查身份验证并自动重定向到登录状态? [英] How to check authentication and automatically redirect to login state with ui-router?

查看:24
本文介绍了如何使用 ui-router 检查身份验证并自动重定向到登录状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在 angularjs 的 run 中有这个函数(运行 AngularJS v1.2.26)

so I have this function in my run in angularjs (running AngularJS v1.2.26)

.run(function(....) {
    authService.authCheck();

    $rootScope.$on('$routeChangeStart', function(event, next, current) {
        if (next.requireLogin) {
            if (!authService.isLoggedIn()) {
                $location.path('/login');
                event.preventDefault();
            }
        }
    });

})...

当直接访问需要身份验证的 URL 时,例如http://127.0.0.1:8080/secret,该函数总是重定向到登录路径,显然调试一段时间后它一直评估为false.当访问默认页面然后转到指定的路线时,它运行没有任何问题.

when directly accessing a URL that requires authentication e.g. http://127.0.0.1:8080/secret, the function always redirects to the login path, clearly after debugging it for a while it evaluates to false all the time. when accessing default page then going to the specified route it runs without any problems.

这是我的authService

this.authCheck = function() {
    $http({
        method: 'PUT',
        url: '/api/login'
    }).
    success(function(data, status, headers, config) {
        if (status === 200) {
            userIsAuthenticated = true;
        } else {
            userIsAuthenticated = false;
        }
        $rootScope.loginStatus = userIsAuthenticated;
    }).
    error(function(data, status, headers, config) {
        userIsAuthenticated = false;
        $rootScope.loginStatus = userIsAuthenticated;
    });
};

this.isLoggedIn = function() {
    return userIsAuthenticated;
};

所以每次我在 !authService.isLoggedIn() 上有一个断点时,我都会看到它的计算结果为 false,即使运行块中的函数在到达 之前尝试对其进行身份验证$rootScope.$on 函数.

So every time I have a break point on !authService.isLoggedIn() I see that it evaluates to false even though the function in the run block tries to authenticate it before reaching the $rootScope.$on function.

究竟是什么阻止了 userIsAuthenticated 变量的状态持久化?

What exactly is preventing the state of userIsAuthenticated variable from being persistent?

推荐答案

authService 中的 .authCheck 是异步的,这意味着 userIsAuthenticated> 不会被设置为 true 直到它第一次真正完成.如果您遵循现在的路线,则必须编写一些更复杂的代码,以便在检查尚未完成时进行等待,然后进行重定向.然而,这是一个凌乱的次优选项.

The .authCheck in your authService is asynchronous, which means that userIsAuthenticated won't be set to true until it actually finishes for the first time. If you followed the route you're on now, you'd have to write some more complex code for waiting if the check isn't completed yet and then redirecting. However, that's a messy sub-optimal option.

最好的方法是让 ui-router 为您解决这个问题.为所有需要登录的状态创建一个共同的祖先状态,例如'会话'.然后使用 resolve 选项使该状态的解析等待您的身份验证检查.如果未通过身份验证,请创建一个特定的状态转移拒绝错误,您可以在其他地方捕获并采取行动(重定向到登录).

The best way to go here is to let ui-router work this out for you. Create a common ancestor state for all your states that require login, e.g. 'session'. Then make that state's resolution wait for your authentication check using resolve option. If not authenticated, create a specific state transfer rejection error, which you can elsewhere catch and act upon (redirect to login).

.state('session', {
    resolve: {
        authentication: ['authService', '$q', function (authService, $q) {
            return authService.checkAuthentication().then(function () {
                if (!authService.isAuthenticated) {
                    return $q.reject({
                        notAuthenticated: true
                    });
                }
            });
        }]
    },
    // ...
})
.state('secret', {
    parent: 'session',
    // ...
});

然后

$rootScope.$on('$stateChangeError', function (_0, _1, _2, _3, _4, error) {
    if (error.notAuthenticated) {
        $state.go('login');
    }
});

(您还需要从身份验证检查中正确返回)

(you'll need to properly return from your authentication check as well)

checkAuthentication: function () {
    return $http({...})
        .success(...)
        .error(...);
}

这篇关于如何使用 ui-router 检查身份验证并自动重定向到登录状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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