Angular 身份验证和访问控制

Angular Authentication and Access control

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

如何在 Angular 中以最佳方式实现它?

谢谢, MSK

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

  1. 身份验证服务

'use strict';

app.factory('Auth', function Auth($http, $cookies, $q) {
    this.login = //...
    this.isLoggedIn = //... point to your REST services
});

  1. 通过ui-router控制何时需要认证

      .state('settings', {
        url: '/settings',
        authenticate: true //add this to state where user needs to be authenticated
      });

  1. 存储和检索令牌

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. 检查某些状态并在需要时重定向

  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');
          }
        });
      }
    });