【问题标题】:Angular: how to download file without showing access_token in urlAngular:如何下载文件而不在 url 中显示 access_token
【发布时间】:2017-01-27 11:19:42
【问题描述】:

我的 Web 应用程序受 Oauth2 保护。对于 ajax 调用,必须在请求文件夹中提供 access_token。例如,这是 factory.js 中的方法之一:

   service.getAll = function () {
        var url = SERVER + "/ristore/foundation/";
        return $http({
            headers: {'Authorization': 'Bearer ' + $window.localStorage.getItem("access_token")},
            url: url,
            method: 'GET',
            crossOrigin: true
        })
    }

现在我想从网页下载一个文件。该文件通过流式传输从服务器传递给客户端:

@RequestMapping(
        value = "/ristore/foundation/xml/{filename}",
        method = RequestMethod.GET,
        produces = "application/xml")
public ResponseEntity<byte[]> downloadXMLFile(@PathVariable String filename) throws IOException {
    FileSystemResource xmlFile = new FileSystemResource("/rsrch1/rists/moonshot/data/prod/foundation/xml/" + filename + ".xml");
    byte [] content = new byte[(int)xmlFile.contentLength()];
    IOUtils.read(xmlFile.getInputStream(), content);

    return ResponseEntity.ok()
        .contentType(MediaType.parseMediaType("application/octet-stream"))
        .contentLength(xmlFile.contentLength())
        .body(content);
}

在html中,我在将被点击开始下载的按钮上指定了ng-click():

        <td data-title="'File'" class="text-center"><span class="glyphicon glyphicon-download-alt" ng-click="download(report.filename)"></span></a>
            </td>

根据这篇帖子Download files in Javascript with OAuth2的回答,$window.open用于处理我的控制器中的url:

  $scope.download = function(filename) {
        var url = "http://rcdrljboss01a:9880/ristoreService/ristore/foundation/xml/" + filename + "?access_token=" + $window.localStorage.getItem("access_token");
        $window.open(url);
    }

我可以通过这种方式下载文件,但是 access_token 显示在下载 url 中。有没有办法在 url 中隐藏 access_token?

【问题讨论】:

    标签: angularjs spring oauth access-token


    【解决方案1】:

    您应该将访问令牌放在标头而不是查询参数中。

    tutorial 详细说明了它的工作原理。

    编辑:有没有办法将令牌添加到 wondow.open(..) 的标头?

    不行,好像不能直接改window.open(..)的header

    你可以做什么:

    用ajax获取xml,打开一个新窗口并将文件设置为窗口内容(伪代码,可能需要将内容转换为字符串):

    var win = open('some-url','windowName','height=300,width=300');
    win.document.write(content);
    

    【讨论】:

    • 我确实将 access_token 放在了所有其他请求(如帖子)的标题中。但现在我使用 $window.open 作为 url。如果有办法为此使用标题,我会这样做的。
    猜你喜欢
    • 2017-10-09
    • 2014-11-21
    • 2013-12-26
    • 2023-03-25
    • 2013-03-05
    • 2018-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多