基于请求体的AngularJS Resource身份验证标头

3
我正在尝试使用 HMAC 认证方法保护的 API,需要将 "Authentication" 标头附加到请求中。
在此示例代码中,我使用 GET 从 API 获取文章,并使用 "update" 自定义方法对其进行更新。为了进行更新,我需要 Authentication 标头。问题是当我定义标头时,$scope.article 为 undefined。
getAuth 函数计算签名。
有什么建议吗?
function EditCtrl($scope,$resource,articleId) {
    var Article = $resource('/blog/articles/:articleId',
    {articleId:articleId}, {
        update: {
            method:'PUT',
            headers: {Authentication: getAuth('key','PUT','/blog/articles/'+articleId,$scope.article)}
        }
    });

    var article = Article.get();
    $scope.article = article;

    $scope.save = function(){
        article.$update();
    }
}

function getAuth(key,verb,resource,data) {
    //data is undefined there

    content_md5 = CryptoJS.MD5(JSON.stringify(data));
    message = verb+'\n'+resource+'\n'+content_md5;
    hash = CryptoJS.HmacSHA512(message, key);

    var sign = "AuthHMAC 0123456789:"+hash.toString(CryptoJS.enc.Base64);

    return sign;
}

要设置动态身份验证,您必须使用请求拦截器来动态设置身份验证。 - Ajay Beniwal
我只发现了HTTP响应拦截器 - Adriano Foschi
让我试着为您设置一个 Plunker。 - Ajay Beniwal
Plunker 可能并不是最佳解决方案,但这是一个非常好的解决办法。http://plnkr.co/edit/Iwk6gTdqYZAvXgRWROIc?p=preview - Ajay Beniwal
4个回答

0

我现在正在做类似的事情。

我相信答案在于使用 $httpProvider.defaults.transformRequest 函数,虽然我还没有完全完成,但基本的步骤如文档中描述的那样:http://docs.angularjs.org/api/ng.$http

我认为是这样的:

var authModule = angular.module('my.AuthModule', [], myAuthModuleCfg);

function myAuthModuleCfg($httpProvider) {
    $httpProvider.defaults.transformRequest.push(myRequestSigner)
}

function myRequestSigner(data, headersGetter) {
    // do some signing, etc...
}

0

我使用三个元素改进了Alan的解决方案:

  • 共享密钥的工厂服务
  • 发送httpRequest的控制器
  • 设置标头的httpRequestInterceptor

控制器调用由工厂服务提供的setKey()来计算标头。最后,httpResponseInterceptor通过调用由工厂服务提供的getKey()来设置请求的标头。

问题解决!


您是否有关于定义和使用拦截器的指导? - Stephane

0

-1

我没有尝试过,但是如果你查看更低级别的API $http,它有一个接受配置参数的方法。我认为这个配置包含了headers属性,你可以在发出请求之前更新它。这是PUT的签名:

$http.put(url, data, config)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接