角智威汤逊Authorization头例外 [英] Angular-JWT Authorization header exception

查看:280
本文介绍了角智威汤逊Authorization头例外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图通过角上传到我的AngularJS应用integreate Cloudinary。但是,我也遇到过试图从我的应用程序上传时,这个错误:

I've been trying to integreate Cloudinary via angular-upload into my AngularJS app. However, I have encountered this error when attempting to upload from my app:

授权不被访问控制允许报头允许

起初我以为这是一个繁重的问题,因为我是使用HTTP的服务器来运行Cloudinary示例应用程序,它上传成功,但现在我已经意识到这一点更容易使用Auth0的角JWT执行的结果。这是附加授权头所有请求,这cloudinary不接受。我发现有人用这里非常类似的问题。

At first I thought this was a grunt issue since I was using http-server to run the Cloudinary sample app, which uploaded successfully, but I have now realized this is more likely a result of using Auth0's angular-jwt implementation. This is attaching the Authorization header to all requests, which cloudinary does not accept. I found someone with a very similar problem here

https://github.com/DaftMonk/generator-angular-fullstack/问题/ 931

不过,我有麻烦搞清楚如何去适应这样的解决方案,以角智威汤逊。我称之为

however, I'm having trouble figuring out how to adapt such a solution to angular-jwt. I call

$ httpProvider.interceptors.push('jwtInterceptor');

在我的app.config,但我想它排除请求 https://api.cloudinary.com/v1_1/

in my app.config, but I want it to exclude requests to https://api.cloudinary.com/v1_1/

这是角智威汤逊分布:

(function() {


// Create all modules and define dependencies to make sure they exist
// and are loaded in the correct order to satisfy dependency injection
// before all nested files are concatenated by Grunt

// Modules
angular.module('angular-jwt',
    [
        'angular-jwt.interceptor',
        'angular-jwt.jwt'
    ]);

 angular.module('angular-jwt.interceptor', [])
  .provider('jwtInterceptor', function() {

    this.urlParam = null;
    this.authHeader = 'Authorization';
    this.authPrefix = 'Bearer ';
    this.tokenGetter = function() {
      return null;
    }

    var config = this;

    this.$get = ["$q", "$injector", "$rootScope", function ($q, $injector, $rootScope) {
      return {
        request: function (request) {
          if (request.skipAuthorization) {
            return request;
          }

          if (config.urlParam) {
            request.params = request.params || {};
            // Already has the token in the url itself
            if (request.params[config.urlParam]) {
              return request;
            }
          } else {
            request.headers = request.headers || {};
            // Already has an Authorization header
            if (request.headers[config.authHeader]) {
              return request;
            }
          }

          var tokenPromise = $q.when($injector.invoke(config.tokenGetter, this, {
            config: request
          }));

          return tokenPromise.then(function(token) {
            if (token) {
              if (config.urlParam) {
                request.params[config.urlParam] = token;
              } else {
                request.headers[config.authHeader] = config.authPrefix + token;
              }
            }
            return request;
          });
        },
        responseError: function (response) {
          // handle the case where the user is not authenticated
          if (response.status === 401) {
            $rootScope.$broadcast('unauthenticated', response);
          }
          return $q.reject(response);
        }
      };
    }];
  });

 angular.module('angular-jwt.jwt', [])
  .service('jwtHelper', function() {

    this.urlBase64Decode = function(str) {
      var output = str.replace(/-/g, '+').replace(/_/g, '/');
      switch (output.length % 4) {
        case 0: { break; }
        case 2: { output += '=='; break; }
        case 3: { output += '='; break; }
        default: {
          throw 'Illegal base64url string!';
        }
      }
      return decodeURIComponent(escape(window.atob(output))); //polifyll https://github.com/davidchambers/Base64.js
    }


    this.decodeToken = function(token) {
      var parts = token.split('.');

      if (parts.length !== 3) {
        throw new Error('JWT must have 3 parts');
      }

      var decoded = this.urlBase64Decode(parts[1]);
      if (!decoded) {
        throw new Error('Cannot decode the token');
      }

      return JSON.parse(decoded);
    }

    this.getTokenExpirationDate = function(token) {
      var decoded;
      decoded = this.decodeToken(token);

      if(typeof decoded.exp === "undefined") {
        return null;
      }

      var d = new Date(0); // The 0 here is the key, which sets the date to the epoch
      d.setUTCSeconds(decoded.exp);

      return d;
    };

    this.isTokenExpired = function(token, offsetSeconds) {
      var d = this.getTokenExpirationDate(token);
      offsetSeconds = offsetSeconds || 0;
      if (d === null) {
        return false;
      }

      // Token expired?
      return !(d.valueOf() > (new Date().valueOf() + (offsetSeconds * 1000)));
    };
  });

}());

帮助?

推荐答案

jwtInterceptor 检查的 skipAuthorization 标志的要求,并且不会发送授权头,如果它被设置为真正

jwtInterceptor checks the request for a skipAuthorization flag, and does not send the Authorization header if it was set to true.

建立你的$ HTTP调用像

Build your $http call like

$http({
    url: 'https://api.cloudinary.com/v1_1/',
    skipAuthorization: true,
    method: 'POST',
    // ... etc
}).then(successCallback, errorCallback);

- 在更多 angular-智威汤逊文档

- More at angular-jwt Docs

这篇关于角智威汤逊Authorization头例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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