Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
447 views
in Technique[技术] by (71.8m points)

oauth - Download files in Javascript with OAuth2

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...