防止 Angular 网站上未经授权的用户在被重定向到登录之前瞬间看到网站的最佳方法?

Best way to prevent unauthorized user on Angular site from seeing site for a split second before being redirected to login?

我目前正在一个站点上构建一个 Angular 前端,该站点从需要通过登录授权的 API 中提取大部分数据。

我构建了以下 authInterceptor,它运行良好并在服务器发送 401 错误时将用户重定向到登录页面:

angular
  .module('myApp.services')
  .factory('authInterceptor', ['$rootScope', '$q', '$window', '$location', function($rootScope, $q, $window, $location) {

    return {
        'request': function(config) {
          config.headers = config.headers || {};
          if ($window.sessionStorage.token) {
            config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
          }

          return config;
        },
        'response': function(response) {
          return response || $q.when(response);
        },
        responseError: function(rejection){
          if (rejection.status == 401){
            $location.path('#/login');
          }
          return $q.reject(rejection);
        }

      };
  }])

这个问题是 API 调用,因此,直到页面加载过程结束才会出现 401 错误 - 因此,用户可以看到所有元素的瞬间(例如,HTML、CSS、图像和所有其他未命中 API 的元素)在应用程序命中 API 并获取401.

我通过在 MainController 的开头随机调用 API 解决了这个问题,它实际上没有做任何事情,但这似乎是错误的方法,因为我正在制作对服务器不必要的 ping。对此有什么建议和最佳做法吗?

此外,当我访问那些未经授权的路由时,我在控制台中收到难看的 401 错误消息 - 有没有一种方法可以在不向用户显示这些消息的情况下执行此重定向,或者这是否正常?

如果您将 ui-router 用于您的应用程序路由,您可以在 'authenticated' 状态的父级中使用嵌套状态和 resolve 子句以确保您只能到达那个controller/template 如果您的 'login' 请求已成功解决,如果请求失败则重定向到 'sign-in' 状态。

这里有一些关于如何使用 ui-router 保护您的 'authenticated' 路由的 gui舞蹈:

http://blog.john.mayonvolcanosoftware.com/protecting-routes-in-angularjs/

我认为 ng-cloak 可以在这里帮助您,因为您可以将它添加到应该隐藏的元素,直到您的应用程序被引导,我已经做了类似的事情,我会尝试给您一个例子