检查 401 然后重定向 Angularjs 但仅在某些路线上 [英] Check for 401 then redirect Angularjs but only on certain routes

查看:27
本文介绍了检查 401 然后重定向 Angularjs 但仅在某些路线上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很好的 angular 服务,它通过查看服务器是否返回 401 错误消息来检查用户是否已登录.如果是,则将用户重定向到登录页面.

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.

这很有效,但问题是它对我的所有页面都是完全全局的.我有一个位于 /explore 的特殊路由(顺便说一句,使用 UI 路由器),我想忽略任何 401 并显示页面,而无需重定向到登录页面.我将如何为 /explore 设置例外?我的代码目前如下:

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

或者你可以使用 $state.includes() 如果你想使用 ui-router's 状态.如果上述方法不起作用,请提供一个小插曲来演示问题.

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.

关于@Kanh TO 关于客户端能够查看未授权页面的评论,我们所做的是处理客户端受限路由,但我们的 Web API 端点会检查身份验证/授权请求,因此即使用户确实摆弄这并设法到达未经授权的路线,他们只会看到没有数据的视图,在我看来这没什么大不了的,因为数据是您希望未经授权的用户看不到的,而不是您应用的视图.

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.

这篇关于检查 401 然后重定向 Angularjs 但仅在某些路线上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆