分享

security

 huhuwoo 2015-10-10

I have a simple app I'm building using Play + AngularJS that requires authentication before most routes can be accessed. The login flow includes a "remember me" feature that stores a session ID in to the browser local storage and gets mapped to a valid authorized database session entry on the server side any time a user returns to the app.

The problem I'm having is that I do the session checking (extract cookie & compare against server) in the run() function of the module:

    .run(function ($rootScope, $http, $cookieStore, $location) {
        // <snip>

        // check if there is already a session?
        var sessionId = window.localStorage["session.id"];
        if (sessionId == null) {
            sessionId = $cookieStore.get("session.id");
        }

        if (sessionId != null) {
            $http.get("/sessions/" + sessionId)
                .success(function (data) {
                    $http.defaults.headers.common['X-Session-ID'] = data.id;
                    $cookieStore.put("session.id", data.id);

                    $rootScope.user = data.user;
                })
                .error(function () {
                    // remove the cookie, since it's dead
                    $cookieStore.remove("session.id");
                    window.localStorage.removeItem("session.id");
                    $location.path("/login");
                });
        } else {
            if ($location.path() != "/login" && $location.path() != "/signup") {
                $location.path("/login");
            }
        }
    });

The problem is that this function executes an AJAX call and I don't know if the session is valid until it completes. However, the controller that loads (via the route selected by $routeProvider) can fire away another AJAX call that often kicks off before the other one finishes, resulting in a race condition and the initial request getting a 401 response code.

So my question is: how can I force run (with its associated $http call) to complete before any other part of the app runs? I have tried using $q/promise here and it doesn't seem to make a difference (perhaps run functions don't honor promises). I've been advisor to use resolve feature in $routeProvider but I don't know exactly what to do and I'm not super execited about having to put that in for every route anyway.

I assume this is a pretty common use case and it gets solved every day. Hopefully someone can give me some direction with my code, or share their approaches for "remember me" and AngularJS.

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多