检查401然后重定向Angularjs但仅限于某些航线航线、重定向、Angularjs

2023-09-13 05:08:16 作者:敬你春风野马

我已经有了一个很好的角度服务,检查,看看用户是否通过查看如果服务器返回401错误信息登录。如果是这样,用户将被重定向到登录页面。

这工作得很好,但问题是,它完全对所有我的网页全球。我有一个驻留在特殊的路由 /探索(使用UI路由器BTW),我想忽略任何401S反正显示在页面不重定向到登录页面。我如何去让这个例外的 /探索?我的code是目前如下:

  .factory('authHtt presponseInterceptor',['$ Q','$位置',函数($ Q $位置){      返回{          回应:功能(响应){              如果(response.status === 401){              }              返回响应|| $ q.when(响应);          },          responseError:函数(拒绝){              如果(rejection.status === 401){                  $ location.path('/欢迎');              }              返回$ q.reject(拒绝);          }      };  }]) 

解决方案 如何查看angularjs版本

这应该工作,传递希望用户被重定向上的具体路径:

  VAR reservedPaths = ['/探索','/教师','/报道'];如果(rejection.status === 401&放大器;&放大器; _.contains(reservedPaths,$ location.path()修剪()){        $ location.path('/欢迎');} 

或者你可以使用 $ state.includes()如果你想与工作UI路由器的状态。提供小普拉克来演示问题,如果以上不工作。

关于@Kanh TO的有关客户端能够查看未授权的网页评论,我们要做的是我们处理的限制路由客户端,但我们的Web API端点检查认证/授权请求,因此即使用户不拨弄这一点,并设法在未经核准的路段到达时,他们简直会看到任何数据,这在我看来是没有什么大不了的景色,因为数据是你想要未经授权的用户无法看到,而不是你的应用程序的看法是什么。

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

解决方案

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.