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
1.2k views
in Technique[技术] by (71.8m points)

angularjs - how to add authentication header to $window.open

I have angularjs application where users enter data that is saved to database, then on server side it is compiled into pdf file. All access requires appropriate authentication headers in place. After needed data is filled a user presses button to save data and then to retrieve pdf file. Optimally, I call $window.open(url_generating_pdf) in my angularjs app. This works well and opens in another window, but how to add authentication header to this $window request? In my understanding I cannot download pdf, and print it with ajax, so I am missing this authentication. Or would there be other ways to call url from server, and make the file open in another window?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I think I should update this old question with a correct and secure answer.

You can not add any headers in the HTTP GET request performed by window.open.

The secure way to make an authenticated request is to set the authentication token into a request header, and avoid exposing it into the URL, as my previous answer suggested (I have learned a some things since then).

To download a PDF (or any other binary data) from an authenticated server with AngularJS you should:

  1. Make an HTTP GET request to the resource sending the authentication token in a header, setting its responseType to a binary data type, for example blob or arraybuffer.
  2. Download the binary data in a file using the "Save As" dialog from the browser, usually creating a download link for the binary data and clicking it.

I hope this answer to clear doubts on this question and provides a secure way to download a resource from an authenticated REST API.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
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

...