简体   繁体   中英

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

I am currently building an Angular front end on a site that pulls much of its data from an API that requires authorization via login.

I have built the following authInterceptor that works well and redirects users to the login page if a 401 error is sent from the server:

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

      };
  }])

The problem with this is that the API calls and therefore, the 401 errors don't occur until the end of the page load process - so, users can see a split second of all of the elements (eg, HTML, CSS, images and all other elements that don't hit the API) loading up on my page before the application hits the API and gets the 401.

I've worked around this by putting a random API call right at the beginning of my MainController that doesn't really do anything but this seems like the wrong way to do it since I'm making an unnecessary ping to the server. Any suggestions and best practices around this?

Also, when I do hit those unauthorized routes, I get the ugly 401 error messages in my console - is there a way to do this redirect without displaying those to the user or is this normal?

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

If you use a ui-router for your application routing, you could use nested states and a resolve clause in a parent of your 'authenticated' states to make sure that you only get to that controller/template if your 'login' request has successfully resolved and to redirect to a 'sign-in' state if the request fails.

Here is some guidance on how to protect your 'authenticated' routes using ui-router:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM