0

我正在尝试构建一个 Web 应用程序,该应用程序应获取预签名的 Amazon S3 URL,然后使用 Knox 将文件上传到该 URL。

但是,当我尝试访问我的存储桶时,S3 给了我这个错误

<Error><Code>InvalidArgument</Code><Message>Only one auth mechanism allowed; only the X-Amz-Algorithm query parameter, Signature query string parameter or the Authorization header should be specified</Message><ArgumentName>Authorization</ArgumentName><ArgumentValue>Bearer *****bearer token*****</ArgumentValue><RequestId>1AFD8C7FD2D7E667</RequestId><HostId>ID</HostId></Error>

我可以看到我对 Amazon 的请求不仅包含我的 Amazon 密钥,还包含我的 Authorization Header

https://bucket.s3-eu-west-1.amazonaws.com/image.jpg?Expires=1418226249&AWSAccessKeyId=<key>&Signature=DHYCio7Oao%2BnzPWiiWkGlHb0NAU%3D

和标题 Authorization:Bearer

代码看起来像

  $http.post(image, data, {headers: { 'Authorization': null }, withCredentials: false}   ).success(function (url) {
        item.images[0] = url;
        $http.post('/api/item', item);
      });

对于不指向我的域的请求,如何摆脱授权令牌?

问候

4

1 回答 1

0

您应该使用拦截器并将其定义为向 $httpProvider 注册的服务工厂,方法是将它们添加到 $httpProvider.interceptors 数组中。工厂被调用并注入依赖项(如果指定)并返回拦截器。

我假设我的授权令牌存储在 cookie 中,并且我想将此令牌作为授权标头传递。因此,为了实现它,我做了什么,它对我有用。

//Token Interceptor to intercept HTTP_AUTHORIZATION token into headers.
App.factory('TokenInterceptor', [ '$q', '$window', '$location', function ($q, $window, $location) {
return {
    request: function (config) {
        config.headers = config.headers || {};
        if ($window.sessionStorage.token) {
            config.headers.Authorization = $window.sessionStorage.token;
        }
        return config;
    },

    requestError: function(rejection) {
        return $q.reject(rejection);
    },

    /* Set Authentication.isAuthenticated to true if 200 received */
    response: function (response) {
        if (response !== null && response.status === 200 && $window.sessionStorage.token && !$window.sessionStorage.isAuthenticated) {
            $window.sessionStorage.isAuthenticated = true;
        }
        return response || $q.when(response);
    },

    /* Revoke client authentication if 401 is received */
    responseError: function(rejection) {
        if (rejection !== null && rejection.status === 401 && ($window.sessionStorage.token || $window.sessionStorage.isAuthenticated)) {
            delete $window.sessionStorage.token;
            $window.sessionStorage.isAuthenticated = false;
            $location.path('/');
        }

        return $q.reject(rejection);
    }
};
}]);

一旦你编写了上述服务,你必须像这样将此拦截器推送到 $httpProvider.interceptors 数组中

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

现在,每次您发出任何 http 请求时,此 Authorization 标头都会自动添加到标头中。

谢谢

于 2014-12-11T08:51:29.353 回答