角度身份验证和访问控制

时间:2016-01-07 03:38:02

标签: angularjs yeoman-generator-angular

我刚刚从Marionette.js转移到Angular。现在我正在创建一个应用程序,其中有一个登录屏幕和主屏幕,我有两个休息api一个用于身份验证,另一个用于检查用户是否有活动会话(使用令牌)。如果用户有活动会话,我想将他重定向到主屏幕。

如何以最佳方式在Angular中实现此功能?

谢谢, MSK

注意:我使用yeoman / generator-angular和ui-router

1 个答案:

答案 0 :(得分:1)

  1. 身份验证服务
  2. 'use strict';
    
    app.factory('Auth', function Auth($http, $cookies, $q) {
        this.login = //...
        this.isLoggedIn = //... point to your REST services
    });

    1. 需要进行身份验证时通过ui-router进行控制
    2.       .state('settings', {
              url: '/settings',
              authenticate: true //add this to state where user needs to be authenticated
            });

      1. 存储和检索令牌
      2. app.config(function($httpProvider) {
            //add interceptor to add authentication header to be verified on the server
            $httpProvider.interceptors.push('authInterceptor');
          })
        
        app.factory('authInterceptor', function($cookies) {
            var state;
            return {
              // Add authorization token to headers
              request: function(config) {
                config.headers = config.headers || {};
                if ($cookies.get('token')) {
                  config.headers.Authorization = 'Bearer ' + $cookies.get('token');
                }
                return config;
              }
            };
        });

        1. 检查某些状态并根据需要重定向
        2.   app.run(function($rootScope, $state, Auth) {
              // Redirect to login if route requires authentication
              $rootScope.$on('$stateChangeStart', function(event, next) {
                if (next.authenticate) {
                  Auth.isLoggedIn(function(loggedIn) {
                    if (!loggedIn) {
                      event.preventDefault();
                      $state.go('login');
                    }
                  });
                }
              });