ddd ddd - 4 months ago 39
AngularJS Question

Angular: how to download file without showing access_token in url

My web application is secured by Oauth2. For ajax calls, the access_token has to be provided in the request folder. For example, here is one of the methods in 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

Now I would like to download a file from the webpage. The file is passed to client from server with streaming:

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()

In html, I specify the ng-click() on the button that will be clicked to start downloading:

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

Based on the answer to this post Download files in Javascript with OAuth2,
is used to handle the url in my controller:

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

I am able to download file this way, but the access_token is shown in the downloading url. Is there a way to hide the access_token in the url?


You should put the access token in the header instead of in the query parameter.

This tutorial shows how this works in detail.

Edit : Is there a way to add the token to the header of wondow.open(..) ?

No, it seems not to be possible to directly change the header for window.open(..)

What you can do :

Get the xml with ajax, open a new window and set the file as content of the window (pseudo code, you may need to convert the content to string):

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