71

Angular+RESTful Client-side Communication w/ API for Auth/(re)Routing

This has been covered in a few different questions, and in a few different tutorials, but all of the previous resources I've encountered don't quite hit the nail on the head.

In a nut-shell, I need to

  • Login via POST from http://client.foo to http://api.foo/login
  • Have a "logged in" GUI/component state for the user that provides a logout route
  • Be able to "update" the UI when the user logs out / logs out. This has been the most frustrating
  • Secure my routes to check for authenticated-state (should they need it) and redirect the user to the login page accordingly

My issues are

  • Every time I navigate to a different page, I need to make the call to api.foo/status to determine whether or not user is logged in. (ATM I'm using Express for routes) This causes a hiccup as Angular determines things like ng-show="user.is_authenticated"
  • When I successfully login/logout, I need to refresh the page (I don't want to have to do this) in order to populate things like {{user.first_name}}, or in the case of logging out, empty that value out.
// Sample response from `/status` if successful 

{
   customer: {...},
   is_authenticated: true,
   authentication_timeout: 1376959033,
   ...
}

What I've tried

Why I feel like I'm losing my mind

  • It seems as though every tutorial relies on some database (lots of Mongo, Couch, PHP+MySQL, ad infinitum) solution, and none rely purely on communication with a RESTful API to persist logged-in states. Once logged in, additional POSTs/GETs are sent with withCredentials:true, so that's not the issue
  • I cannot find ANY examples/tutorials/repos that do Angular+REST+Auth, sans a backend language.

I'm not too proud

Admittedly, I'm new to Angular, and would not be surprised if I'm approaching this in a ridiculous way; I'd be thrilled if someone suggest an alternative—even if it's soup-to-nuts.

I'm using Express mostly because I really love Jade and Stylus— I'm not married to the Express' routing and will give it up if what I want to do is only possible with Angular's routing.

Thanks in advance for any help anyone can provide. And please don't ask me to Google it, because I have about 26 pages of purple links. ;-)


1This solution relies on Angular's $httpBackend mock, and it's unclear how to make it talk to a real server.

2This was the closest, but since I have an existing API I need to authenticate with, I could not use passport's 'localStrategy', and it seemed insane to write an OAUTH service...that only I intended to use.

4

4 回答 4

35

这取自我关于 url 路由授权和元素安全的博客文章,我将简要总结要点 :-)

前端 Web 应用程序的安全性只是阻止 Joe Public 的一个开始措施,但是任何具有一些 Web 知识的用户都可以绕过它,因此您应该始终拥有服务器端的安全性。

Angular 中安全性的主要关注点是路由安全,幸运的是,在 Angular 中定义路由时,您将创建一个对象,一个可以具有其他属性的对象。我的方法的基石是向此路由对象添加一个安全对象,该对象基本上定义了用户必须具有的角色才能访问特定路由。

 // route which requires the user to be logged in and have the 'Admin' or 'UserManager' permission
    $routeProvider.when('/admin/users', {
        controller: 'userListCtrl',
        templateUrl: 'js/modules/admin/html/users.tmpl.html',
        access: {
            requiresLogin: true,
            requiredPermissions: ['Admin', 'UserManager'],
            permissionType: 'AtLeastOne'
        });

整个方法侧重于授权服务,该服务基本上检查用户是否具有所需的权限。该服务将关注点从该解决方案的其他部分中抽象出来,与用户及其在登录期间从服务器检索到的实际权限有关。虽然代码非常冗长,但在我的博客文章中进行了充分解释。但是,它主要处理权限检查和两种授权模式。第一个是用户必须至少拥有一个定义的权限,第二个是用户必须拥有所有定义的权限。

angular.module(jcs.modules.auth.name).factory(jcs.modules.auth.services.authorization, [  
'authentication',  
function (authentication) {  
 var authorize = function (loginRequired, requiredPermissions, permissionCheckType) {
    var result = jcs.modules.auth.enums.authorised.authorised,
        user = authentication.getCurrentLoginUser(),
        loweredPermissions = [],
        hasPermission = true,
        permission, i;

    permissionCheckType = permissionCheckType || jcs.modules.auth.enums.permissionCheckType.atLeastOne;
    if (loginRequired === true && user === undefined) {
        result = jcs.modules.auth.enums.authorised.loginRequired;
    } else if ((loginRequired === true && user !== undefined) &&
        (requiredPermissions === undefined || requiredPermissions.length === 0)) {
        // Login is required but no specific permissions are specified.
        result = jcs.modules.auth.enums.authorised.authorised;
    } else if (requiredPermissions) {
        loweredPermissions = [];
        angular.forEach(user.permissions, function (permission) {
            loweredPermissions.push(permission.toLowerCase());
        });

        for (i = 0; i < requiredPermissions.length; i += 1) {
            permission = requiredPermissions[i].toLowerCase();

            if (permissionCheckType === jcs.modules.auth.enums.permissionCheckType.combinationRequired) {
                hasPermission = hasPermission && loweredPermissions.indexOf(permission) > -1;
                // if all the permissions are required and hasPermission is false there is no point carrying on
                if (hasPermission === false) {
                    break;
                }
            } else if (permissionCheckType === jcs.modules.auth.enums.permissionCheckType.atLeastOne) {
                hasPermission = loweredPermissions.indexOf(permission) > -1;
                // if we only need one of the permissions and we have it there is no point carrying on
                if (hasPermission) {
                    break;
                }
            }
        }

        result = hasPermission ?
                 jcs.modules.auth.enums.authorised.authorised :
                 jcs.modules.auth.enums.authorised.notAuthorised;
    }

    return result;
};

既然路由具有安全性,您需要一种方法来确定当路由更改开始时用户是否可以访问该路由。为此,我们拦截路由更改请求,检查路由对象(上面有我们的新访问对象),如果用户无法访问视图,我们将路由替换为另一个。

angular.module(jcs.modules.auth.name).run([  
    '$rootScope',
    '$location',
    jcs.modules.auth.services.authorization,
    function ($rootScope, $location, authorization) {
        $rootScope.$on('$routeChangeStart', function (event, next) {
            var authorised;
            if (next.access !== undefined) {
                authorised = authorization.authorize(next.access.loginRequired,
                                                     next.access.permissions,
                                                     next.access.permissionCheckType);
                if (authorised === jcs.modules.auth.enums.authorised.loginRequired) {
                    $location.path(jcs.modules.auth.routes.login);
                } else if (authorised === jcs.modules.auth.enums.authorised.notAuthorised) {
                    $location.path(jcs.modules.auth.routes.notAuthorised).replace();
                }
            }
        });
    }]);

这里的关键实际上是“.replace()”,因为它将当前路由(他们无权查看的路由)替换为我们将他们重定向到的路由。这会阻止任何然后导航回未经授权的路线。

现在我们可以拦截路由,我们可以做很多很酷的事情,包括在用户登陆他们需要登录的路由时在登录后重定向。

解决方案的第二部分是能够根据权限向用户隐藏/显示 UI 元素。这是通过一个简单的指令实现的。

angular.module(jcs.modules.auth.name).directive('access', [  
        jcs.modules.auth.services.authorization,
        function (authorization) {
            return {
              restrict: 'A',
              link: function (scope, element, attrs) {
                  var makeVisible = function () {
                          element.removeClass('hidden');
                      },
                      makeHidden = function () {
                          element.addClass('hidden');
                      },
                      determineVisibility = function (resetFirst) {
                          var result;
                          if (resetFirst) {
                              makeVisible();
                          }

                          result = authorization.authorize(true, roles, attrs.accessPermissionType);
                          if (result === jcs.modules.auth.enums.authorised.authorised) {
                              makeVisible();
                          } else {
                              makeHidden();
                          }
                      },
                      roles = attrs.access.split(',');


                  if (roles.length > 0) {
                      determineVisibility(true);
                  }
              }
            };
        }]);

然后你会确定一个像这样的元素:

 <button type="button" access="CanEditUser, Admin" access-permission-type="AtLeastOne">Save User</button>

阅读我的完整博客文章,了解更详细的方法概述。

于 2014-08-02T08:17:36.647 回答
5

我没有使用 $resource,因为我只是为我的应用程序手工制作服务调用。也就是说,我已经通过拥有一项服务来处理登录,该服务依赖于获得某种初始化数据的所有其他服务。当登录成功时,它会触发所有服务的初始化。

在我的控制器范围内,我观察 loginServiceInformation 并相应地填充模型的一些属性(以触发适当的 ng-show/hide)。关于路由,我使用的是 Angular 的内置路由,我只是有一个基于这里显示的 loggedIn 布尔值的 ng-hide,它显示请求登录的文本或具有 ng-view 属性的 div(因此,如果未登录登录后立即进入正确的页面,目前我为所有视图加载数据,但我相信如有必要,这可能更具选择性)

//Services
angular.module("loginModule.services", ["gardenModule.services",
                                        "surveyModule.services",
                                        "userModule.services",
                                        "cropModule.services"
                                        ]).service(
                                            'loginService',
                                            [   "$http",
                                                "$q",
                                                "gardenService",
                                                "surveyService",
                                                "userService",
                                                "cropService",
                                                function (  $http,
                                                            $q,
                                                            gardenService,
                                                            surveyService,
                                                            userService,
                                                            cropService) {

    var service = {
        loginInformation: {loggedIn:false, username: undefined, loginAttemptFailed:false, loggedInUser: {}, loadingData:false},

        getLoggedInUser:function(username, password)
        {
            service.loginInformation.loadingData = true;
            var deferred = $q.defer();

            $http.get("php/login/getLoggedInUser.php").success(function(data){
                service.loginInformation.loggedIn = true;
                service.loginInformation.loginAttemptFailed = false;
                service.loginInformation.loggedInUser = data;

                gardenService.initialize();
                surveyService.initialize();
                userService.initialize();
                cropService.initialize();

                service.loginInformation.loadingData = false;

                deferred.resolve(data);
            }).error(function(error) {
                service.loginInformation.loggedIn = false;
                deferred.reject(error);
            });

            return deferred.promise;
        },
        login:function(username, password)
        {
            var deferred = $q.defer();

            $http.post("php/login/login.php", {username:username, password:password}).success(function(data){
                service.loginInformation.loggedInUser = data;
                service.loginInformation.loggedIn = true;
                service.loginInformation.loginAttemptFailed = false;

                gardenService.initialize();
                surveyService.initialize();
                userService.initialize();
                cropService.initialize();

                deferred.resolve(data);
            }).error(function(error) {
                service.loginInformation.loggedInUser = {};
                service.loginInformation.loggedIn = false;
                service.loginInformation.loginAttemptFailed = true;
                deferred.reject(error);
            });

            return deferred.promise;
        },
        logout:function()
        {
            var deferred = $q.defer();

            $http.post("php/login/logout.php").then(function(data){
                service.loginInformation.loggedInUser = {};
                service.loginInformation.loggedIn = false;
                deferred.resolve(data);
            }, function(error) {
                service.loginInformation.loggedInUser = {};
                service.loginInformation.loggedIn = false;
                deferred.reject(error);
            });

            return deferred.promise;
        }
    };
    service.getLoggedInUser();
    return service;
}]);

//Controllers
angular.module("loginModule.controllers", ['loginModule.services']).controller("LoginCtrl", ["$scope", "$location", "loginService", function($scope, $location, loginService){

    $scope.loginModel = {
                        loadingData:true,
                        inputUsername: undefined,
                        inputPassword: undefined,
                        curLoginUrl:"partials/login/default.html",
                        loginFailed:false,
                        loginServiceInformation:{}
                        };

    $scope.login = function(username, password) {
        loginService.login(username,password).then(function(data){
            $scope.loginModel.curLoginUrl = "partials/login/logoutButton.html";
        });
    }
    $scope.logout = function(username, password) {
        loginService.logout().then(function(data){
            $scope.loginModel.curLoginUrl = "partials/login/default.html";
            $scope.loginModel.inputPassword = undefined;
            $scope.loginModel.inputUsername = undefined;
            $location.path("home");
        });
    }
    $scope.switchUser = function(username, password) {
        loginService.logout().then(function(data){
            $scope.loginModel.curLoginUrl = "partials/login/loginForm.html";
            $scope.loginModel.inputPassword = undefined;
            $scope.loginModel.inputUsername = undefined;
        });
    }
    $scope.showLoginForm = function() {
        $scope.loginModel.curLoginUrl = "partials/login/loginForm.html";
    }
    $scope.hideLoginForm = function() {
        $scope.loginModel.curLoginUrl = "partials/login/default.html";
    }

    $scope.$watch(function(){return loginService.loginInformation}, function(newVal) {
        $scope.loginModel.loginServiceInformation = newVal;
        if(newVal.loggedIn)
        {
            $scope.loginModel.curLoginUrl = "partials/login/logoutButton.html";
        }
    }, true);
}]);

angular.module("loginModule", ["loginModule.services", "loginModule.controllers"]);

的HTML

<div style="height:40px;z-index:200;position:relative">
    <div class="well">
        <form
            ng-submit="login(loginModel.inputUsername, loginModel.inputPassword)">
            <input
                type="text"
                ng-model="loginModel.inputUsername"
                placeholder="Username"/><br/>
            <input
                type="password"
                ng-model="loginModel.inputPassword"
                placeholder="Password"/><br/>
            <button
                class="btn btn-primary">Submit</button>
            <button
                class="btn"
                ng-click="hideLoginForm()">Cancel</button>
        </form>
        <div
            ng-show="loginModel.loginServiceInformation.loginAttemptFailed">
            Login attempt failed
        </div>
    </div>
</div>

使用上述部分完成图片的 Base HTML:

<body ng-controller="NavigationCtrl" ng-init="initialize()">
        <div id="outerContainer" ng-controller="LoginCtrl">
            <div style="height:20px"></div>
            <ng-include src="'partials/header.html'"></ng-include>
            <div  id="contentRegion">
                <div ng-hide="loginModel.loginServiceInformation.loggedIn">Please login to continue.
                <br/><br/>
                This new version of this site is currently under construction.
                <br/><br/>
                If you need the legacy site and database <a href="legacy/">click here.</a></div>
                <div ng-view ng-show="loginModel.loginServiceInformation.loggedIn"></div>
            </div>
            <div class="clear"></div>
            <ng-include src="'partials/footer.html'"></ng-include>
        </div>
    </body>

我在 DOM 中使用 ng-controller 定义了登录控制器,这样我就可以根据 loggedIn 变量更改页面的正文区域。

注意我还没有在这里实现表单验证。诚然,对于 Angular 来说仍然很新鲜,所以欢迎任何指向这篇文章中的东西的指针。尽管这不能直接回答问题,因为它不是基于 RESTful 的实现,但我相信它可以适用于 $resources,因为它是建立在 $http 调用之上的。

于 2013-08-20T02:27:07.373 回答
5

我已经为UserApp编写了一个AngularJS 模块,它几乎可以满足您的所有要求。您可以:

  1. 修改模块并将函数附加到您自己的 API,或
  2. 将该模块与用户管理 API UserApp一起使用

https://github.com/userapp-io/userapp-angular

它支持受保护/公共路由、登录/注销时重新路由、用于状态检查的心跳、将会话令牌存储在 cookie 中、事件等。

如果您想尝试一下 UserApp,请参加Codecademy 上的课程

以下是它如何工作的一些示例:

  • 带有错误处理的登录表单:

    <form ua-login ua-error="error-msg">
        <input name="login" placeholder="Username"><br>
        <input name="password" placeholder="Password" type="password"><br>
        <button type="submit">Log in</button>
        <p id="error-msg"></p>
    </form>
    
  • 带有错误处理的注册表单:

    <form ua-signup ua-error="error-msg">
      <input name="first_name" placeholder="Your name"><br>
      <input name="login" ua-is-email placeholder="Email"><br>
      <input name="password" placeholder="Password" type="password"><br>
      <button type="submit">Create account</button>
      <p id="error-msg"></p>
    </form>
    
  • 如何指定哪些路由应该是公开的,哪些路由是登录表单:

    $routeProvider.when('/login', {templateUrl: 'partials/login.html', public: true, login: true});
    $routeProvider.when('/signup', {templateUrl: 'partials/signup.html', public: true});
    

    .otherwise()路由应设置为您希望用户在登录后重定向的位置。例子:

    $routeProvider.otherwise({redirectTo: '/home'});

  • 退出链接:

    <a href="#" ua-logout>Log Out</a>

    (结束会话并重定向到登录路由)

  • 访问用户属性:

    使用user服务访问用户信息,例如:user.current.email

    或者在模板中:<span>{{ user.email }}</span>

  • 隐藏仅在登录时才可见的元素:

    <div ng-show="user.authorized">Welcome {{ user.first_name }}!</div>

  • 根据权限显示一个元素:

    <div ua-has-permission="admin">You are an admin</div>

并且要对您的后端服务进行身份验证,只需使用user.token()获取会话令牌并将其与 AJAX 请求一起发送。在后端,使用UserApp API(如果您使用 UserApp)来检查令牌是否有效。

如果您需要任何帮助,请告诉我 :)

于 2013-12-17T00:39:22.410 回答
4

我创建了一个 github 存储库,基本上总结了这篇文章:https ://medium.com/opinionated-angularjs/techniques-for-authentication-in-angularjs-applications-7bbf0346acec

ng-login Github 仓库

普朗克

我会尽量解释清楚,希望对你们中的一些人有所帮助:

(1) app.js:在应用定义上创建认证常量

var loginApp = angular.module('loginApp', ['ui.router', 'ui.bootstrap'])
/*Constants regarding user login defined here*/
.constant('USER_ROLES', {
    all : '*',
    admin : 'admin',
    editor : 'editor',
    guest : 'guest'
}).constant('AUTH_EVENTS', {
    loginSuccess : 'auth-login-success',
    loginFailed : 'auth-login-failed',
    logoutSuccess : 'auth-logout-success',
    sessionTimeout : 'auth-session-timeout',
    notAuthenticated : 'auth-not-authenticated',
    notAuthorized : 'auth-not-authorized'
})

(2) Auth Service:以下所有功能均在 auth.js 服务中实现。$http 服务用于与服务器通信以进行身份​​验证过程。还包含授权功能,即是否允许用户执行特定操作。

angular.module('loginApp')
.factory('Auth', [ '$http', '$rootScope', '$window', 'Session', 'AUTH_EVENTS', 
function($http, $rootScope, $window, Session, AUTH_EVENTS) {

authService.login() = [...]
authService.isAuthenticated() = [...]
authService.isAuthorized() = [...]
authService.logout() = [...]

return authService;
} ]);

(3) Session:保存用户数据的单例。这里的实现取决于你。

angular.module('loginApp').service('Session', function($rootScope, USER_ROLES) {

    this.create = function(user) {
        this.user = user;
        this.userRole = user.userRole;
    };
    this.destroy = function() {
        this.user = null;
        this.userRole = null;
    };
    return this;
});

(4) 父控制器:将其视为您应用程序的“主要”功能,所有控制器都继承自该控制器,它是该应用程序身份验证的支柱。

<body ng-controller="ParentController">
[...]
</body>

(5) 访问控制:要拒绝某些路由的访问,必须执行 2 个步骤:

a)在ui路由器的$stateProvider服务上添加允许访问每个路由的角色数据,如下所示(同样适用于ngRoute)。

.config(function ($stateProvider, USER_ROLES) {
  $stateProvider.state('dashboard', {
    url: '/dashboard',
    templateUrl: 'dashboard/index.html',
    data: {
      authorizedRoles: [USER_ROLES.admin, USER_ROLES.editor]
    }
  });
})

b) 在 $rootScope.$on('$stateChangeStart') 上添加功能以防止用户未授权时状态更改。

$rootScope.$on('$stateChangeStart', function (event, next) {
    var authorizedRoles = next.data.authorizedRoles;
    if (!Auth.isAuthorized(authorizedRoles)) {
      event.preventDefault();
      if (Auth.isAuthenticated()) {
        // user is not allowed
        $rootScope.$broadcast(AUTH_EVENTS.notAuthorized);
      } else {d
        // user is not logged in
        $rootScope.$broadcast(AUTH_EVENTS.notAuthenticated);
      }
    }
});

(6) Auth拦截器:这个实现了,但是不能在这段代码的范围内检查。在每个 $http 请求之后,此拦截器都会检查状态码,如果返回以下之一,则它会广播一个事件以强制用户再次登录。

angular.module('loginApp')
.factory('AuthInterceptor', [ '$rootScope', '$q', 'Session', 'AUTH_EVENTS',
function($rootScope, $q, Session, AUTH_EVENTS) {
    return {
        responseError : function(response) {
            $rootScope.$broadcast({
                401 : AUTH_EVENTS.notAuthenticated,
                403 : AUTH_EVENTS.notAuthorized,
                419 : AUTH_EVENTS.sessionTimeout,
                440 : AUTH_EVENTS.sessionTimeout
            }[response.status], response);
            return $q.reject(response);
        }
    };
} ]);

PS通过添加包含在directives.js 中的指令,可以轻松避免第一篇文章中所述的表单数据自动填充错误。

PS2用户可以轻松调整此代码,以允许看到不同的路线,或显示不应该显示的内容。逻辑必须在服务器端实现,这只是在您的 ng-app 上正确显示内容的一种方式。

于 2014-10-05T01:46:25.467 回答