2

I am developing a RESTful API with Spring Boot and secured with oAuth2.0 (via Spring Security) and my frontend in AngularJS.

I need to download a file and every post I read says (and I understand) that I should use window.open('urlToTheFileEndpoint');

But doing it that way, I cannot add the security header (like all my other ajax request), so the API does not allow my request to be completed.

Is there a way to handle this? Or should I make this file endpoint unsecure?

Fernando Fradegrada
  • 973
  • 1
  • 9
  • 26

2 Answers2

2

This SO thread might be useful:

Download file with a REST request needing headers and giving the content

It also mentions this article:

File Download with HTTP Request Header

Here is a snippet:

var id = 123;
var req = ic.ajax.raw({
    type: 'GET',
    url: '/api/dowloads/'+id,
    beforeSend: function (request) {
        request.setRequestHeader('token', 'token for '+id);
    },
    processData: false
});
Community
  • 1
  • 1
paulsm4
  • 114,292
  • 17
  • 138
  • 190
2

So this is how I'll solve the issue:

When users clicks "download" I'll make an ajax call to the API server, which does not returns the file, but returns a temporary uuid. The server will create a temporary file called uuid.route (i.e: abc-123.route) with the real route to the file (i.e: /mnt/data/files/excel_template.xlsx).

Then when ajax call returns with the uuid, I can call window.open('getFile?uuid=abc-123'). This will be an unsecure endpoint. But once it's downloaded or within an expiration time, this route file will be deleted, so it can never be called again.

That way, it supports any file, any size.

It's my best approach.

Fernando Fradegrada
  • 973
  • 1
  • 9
  • 26