在我的 angularjs 应用程序中,我正在与需要通过 http header 进行基本访问身份验证的后端服务器进行通信。我已经按照描述在客户端实现了身份验证机制 here .
angular.module('myAuthModule')
.config(['$httpProvider', '$stateProvider',
function ($httpProvider, $stateProvider) {
$httpProvider.interceptors.push('securityInterceptor');
}])
.factory('securityInterceptor', ['$location', '$window', '$q',
function ($location, $window, $q) {
return {
request: function (config) {
config.headers = config.headers || {};
if ($window.sessionStorage.token) {
config.headers['Auth-Key'] = $window.sessionStorage.token;
}
return config;
},
response: function (response) {
if (response.status === 401 || response.status === 403) {
$location.path('/login');
}
return response || $q.when(response);
}
};
}
]);
到目前为止一切顺利,在 Angular 应用程序中处理 xhr 请求按预期工作。
问题是我需要提供pdf文档的下载链接。我的后端服务器有一个 /Document/Pdf/:id
资源,它为 application/pdf
响应提供 ContentDisposition: attachment
,这也需要身份验证。我知道我无法使用 xhr 启动下载,但是两者都通过 ngHref
提供文档下载链接并调用一个函数,例如 $window.open('/Document/Pdf/13')
导致服务器返回 401 Unauthorized
响应。
我在这里错过了什么?
最佳答案
在探索了 @Geoff Genz 提供的可能性后,添加了第四个 - data-uri 选项,遗憾的是不允许定义文件名 - 我决定采用不同的方法。
我在 API 中添加了一种方法,它根据正常验证的请求生成一次性下载链接并立即下载。 Angular 处理程序变得非常简单
.factory('fileFactory', ['$http', '$window',
function ($http, $window) {
return {
downloadFile: function (fileId) {
return $http(
{
method: "POST",
data: fileId,
url: '/api/Files/RequestDownloadLink',
cache: false
}).success(function (response) {
var url = '/api/File/' + response.downloadId;
$window.location = url;
});
}
};
}]);
这并不完美,但我觉得至少是 hack-ish。这也适用于我,因为我可以完全控制前端和后端。
关于javascript - 使用 Angular.js - 如何从需要身份验证的后端提供二进制数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21632937/