开发者

How to add an authorization header to a DOM form element?

开发者 https://www.devze.com 2023-02-13 07:56 出处:网络
I am trying to upload a file to a server, and have my DOM element setup as such: _uploadForm = document.createElement(\"form\");

I am trying to upload a file to a server, and have my DOM element setup as such:

        _uploadForm = document.createElement("form");

        _uploadForm.method = "POST";
        _uploadForm.action = "#";

        if(_isBrowser.IE)
            _uploadForm.encoding = "multipart/form-data";
        else
            _uploadForm.enctype = "multipart/form-data";

My server requires an http basic authorization header. How can I pas开发者_StackOverflows that through this DOM element?


Your javascript client is going to have to add headers when submitting the form. I am not sure which javacript client lib you are using, but things like angular do allow you to set default headers or even have interceptors that can add headers before sending.

        var req = {
 method: 'POST',
 url: 'http://example.com',
 headers: {
   'Content-Type': undefined,
   'Authorization':  'your-scheme your-token-perhaps'
 },
 data: { test: 'test' }
}


DOM elements have nothing to do with authorization, they're just the internal browser's representation of the various html tags. Authorization is demanded by the server - if the page is in a protected area, then the server will demand credentials, and that has nothing to do with the form itself.


The easiest way is to serve the upload form and the upload handler from the same folder, and use .htaccess to force Basic authentication for both. Then the browser automatically requests credentials when the upload form is loaded, and the credentials would be sent automatically with the upload (I believe).

However, your best bet is not to use HTTP Basic authentication at all. It sends passwords in clear text on every request unless you're using SSL, and in general, it is a hassle to use.

If you insist on using Basic, I believe it can be done with ActionScript (compiled to an SWF). I also know a way to set an Authorization header on an AJAX call, but you can't upload a file with an AJAX call, and the browser does not remember Authorization headers sent via an AJAX call.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号