Download files in Javascript with OAuth2

♀尐吖头ヾ 提交于 2019-12-18 08:30:07

问题


I'm developing an single-page with Javascript+AngularJS on the client side and Spring MVC + Spring Security OAuth2 on the server side. Spring MVC acts as a REST controller for any AJAX requests from the page.

For authorization, the script sends an "Authorization: Bearer ..." headers with each AJAX request. This works fine when requesting small amounts of data. To download XML files (export user data) I download them via AJAX, using the OAuth2 headers and create a Blob to allow saving the file in the browser:

var blob = new Blob([data.data], {'type': "text/xml"});
var a = document.createElement("a");
a.href = window.URL.createObjectURL(blob);
a.download = "downloaded-file-" + new Date().toISOString() + ".xml";
a.click();

This approach works but

  • Uses RAM and so is unsuitable for large file downloads
  • Does not show a proper progress/loading bar

So, the question is: is there a better way of downloading files with OAuth2 authorization? Javascript does not allow to specify headers when doing redirects, and OAuth does not allow to specify the authorization token via URL parameters. I'm thinking of either

  • adding a special Spring MVC controller method to provide an URL which redirects from an URL-encoded token to a header-encoded HTTP request
  • adding an extra Spring Security filter to allows extracting the token from URL parameters
  • moving to cookie-based authorization instead of OAuth2

If anyone had similar issues, could you please share your approach to this problem?


回答1:


Turns out it's very easy to to in spring-security-oauth2 2.0.7.RELEASE:

Simply pass the access token as the access_token request parameter:

window.open("service/export?access_token=" + access_token);

Now, this will appear with the access token in plaintext in the download history, so for proper security a "logout" option should be properly implemented, or the download will have to be done as a "form post".




回答2:


I would go with cookies if I were you - it takes all the hassle out of it. I wrote some blogs recently to show how easy it is (e.g. https://spring.io/blog/2015/01/20/the-resource-server-angular-js-and-spring-security-part-iii). People get too hung up on "stateless" applications.



来源:https://stackoverflow.com/questions/28384470/download-files-in-javascript-with-oauth2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!