【问题标题】:Simple interceptor that will fetch all requests and add the jwt token to its authorization header简单的拦截器,它将获取所有请求并将 jwt 令牌添加到其授权标头
【发布时间】:2018-01-11 12:59:26
【问题描述】:

在我努力设置受保护页面所需的登录并在未经授权的情况下重新路由到登录页面,同时使用 Django REST Framework 和 DRF-JWT,我正在尝试完成以下教程:

https://www.octobot.io/blog/2016-11-11-json-web-token-jwt-authentication-in-a-djangoangularjs-web-app/

我不确定这在前端部分的第 3 步中是什么样子。

// Add a simple interceptor that will fetch all requests and add the jwt token to its authorization header.

有人可以举个例子吗?

另外,关于我在一般设置中遇到的问题的原始帖子。

Trying to get login required to work when trying to access protected pages

谢谢!

【问题讨论】:

    标签: angularjs django-rest-framework jwt


    【解决方案1】:

    拦截器是注册到 $httpProvider 通过将它们添加到 $httpProvider.interceptors 数组。 调用工厂并注入依赖项(如果指定) 并返回拦截器。

    intercepter 背后的基本思想是,它将在每个 $http 请求之前被调用,您可以使用服务来检查用户是否已登录并添加令牌或其他任何需要添加到标头中。您还可以为对每个 $http 请求的响应添加一些逻辑,例如根据状态代码处理响应。

    以下是您如何在 Angular 中使用它来为每个 http 请求添加访问令牌。

    angular.module('myapp')
    .run(['$rootScope', '$injector', function($rootScope,$injector) {
        $injector.get("$http").defaults.transformRequest = function(data, headersGetter) {
          if (sessionService.isLogged()) {
            headersGetter()['Authorization'] = "Bearer " + sessionService.getAccessToken();
          }
          if (data) {
            return angular.toJson(data);
          }
        };
    });
    

    以下是响应拦截器的使用方法:

    angular.module('myapp')
    .factory('authHttpResponseInterceptor', function($q, $location, sessionService, $http) {
      return {
        response: function(response) {
          //some logic here
          return response || $q.when(response);
        },
        responseError: function(rejection) {
          if (rejection.status === 401) {
            //some logic here
          }
          return $q.reject(rejection);
         }
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2021-07-22
      • 1970-01-01
      • 2015-11-18
      • 1970-01-01
      • 2021-02-19
      • 2019-10-01
      • 2020-06-23
      • 2023-03-23
      • 2017-05-19
      相关资源
      最近更新 更多