不从Angular向AWS发送授权标头

时间:2014-12-11 08:36:34

标签: angularjs amazon-s3 passport.js passport-facebook knox-amazon-s3-client

我正在尝试构建一个应该获取预先签名的Amazon S3 URL的Web应用程序,然后使用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>

我可以看到我对亚马逊的请求不仅包含我的亚马逊密钥,还包含我的授权标题

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

和标题     授权:持票人

代码看起来像

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

如何删除未指向我的域的请求的授权令牌?

此致

1 个答案:

答案 0 :(得分:0)

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

我假设我的授权令牌存储在cookie中,我想将此令牌作为Authorization标头传递。所以要做到这一点,我做了什么,它对我有用。

//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标头都会自动添加到标头中。

由于