如何使用带有Bearer令牌的Angular下载文件

时间:2016-04-26 20:04:05

标签: angularjs passport.js adal azure-active-directory

我们已使用Azure AD + OpenID连接保护了我们的应用程序。客户端应用程序是在Angular中开发的,我们使用'angular-adal'库来与azure广告集成。因此,每当客户端向服务器发出api呼叫时,它会自动在请求头中包含承载令牌。 (在服务器上我们有'passport-azure-ad'节点库来验证令牌)

我们有下载文件功能,目前实现为打击

控制器

    $scope.getURL = function (reportId) {
                return '/api/reports/download/' + reportId;
    };

HTML

     <form method="get" action="{{getURL(row.id)}}">
        <button class="btn btn-link" type="submit">Download Results</button>
     </form>

但是,当我点击下载按钮时,它不会在请求中包含持有者令牌,因此服务器返回未授权的错误。我如何在请求中包含令牌?什么是最好的方式?

UPDATE1
根据{{​​3}}库的建议,我们可以通过在$ routeProvider中将'requiredADLogin'属性设置为true来保护路由。如下所示

    $routeProvider.
         when("/todoList", {
              controller: "todoListController",
              templateUrl: "/App/Views/todoList.html",
              requireADLogin: true
      }); 

我正在使用$ stateProvider。我已经使用'requiredADLogin'为所有其他html页面路由设置了状态,并且工作正常。如何为API路由设置$ stateProvider。我的下载网址是

'/api/reports/download/'+reportID

1 个答案:

答案 0 :(得分:0)

我不熟悉Azure AD,但我猜你需要在标题中设置身份验证令牌:

var req = {
 method: 'GET',
 url: '/api/reports/download/' + reportId,
 headers: {
   'Authorization': 'Bearer ' + token
 }
}

$http(req).then(function(){...}, function(){...});