Frage

I've got a nice angular service that checks to see if a user is logged in by looking to see if the server returns a 401 error message. If it does, the user is redirected to a login page.

This works well, but the issue is that its completely global for all of my pages. I have a special route that resides at /explore (using UI-router btw) that I want to ignore any 401s and show the page anyway without redirecting to the login page. How would I go about making this exception for /explore? My code is currently as follows:

  .factory('authHttpResponseInterceptor',['$q','$location',function($q,$location) {

      return {
          response: function(response){
              if (response.status === 401) {
              }

              return response || $q.when(response);
          },
          responseError: function(rejection) {
              if (rejection.status === 401) {
                  $location.path('/welcome');
              }
              return $q.reject(rejection);
          }
      };
  }])
War es hilfreich?

Lösung

This should work, pass in the specific paths you want the user to be redirected on:

var reservedPaths = ['/explore','/teachers','/reports'];

if (rejection.status === 401 && _.contains(reservedPaths,$location.path().trim()) {
        $location.path('/welcome');
}

Or you could use $state.includes() if you want to work with ui-router's states. Provide a small plunk to demonstrate the issue if the above doesn't work.

Regarding @Kanh TO's comment about the client being able to view unauthorized pages, what we do is we handle the restricted routes client side, but our web API endpoints check requests for authentication/authorization, so even if the user does fiddle with this and manage to arrive at unauthorized routes, they'll simply see a view with no data, which in my opinion is no big deal since the data is what you want unauthorized users to not see, not your app's views.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top