60

Where can I find reference code that implements a HTTP Basic Authentication client in pure JavaScript, suitable for AJAX?

Extra points for code, or pointers to code, that can be used independent of JS toolkits like YUI. No points for Java, Flash/Flex, PHP frameworks, etc.

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
system PAUSE
  • 37,082
  • 20
  • 62
  • 59

2 Answers2

61

The five-parameter version of the XMLHttpRequest.open method allows you to specify the username and password. (WHATWG spec)

xhr.open(method, url, async, username, password)
cambunctious
  • 8,391
  • 5
  • 34
  • 53
Alnitak
  • 334,560
  • 70
  • 407
  • 495
24

There is a good article/tutorial written by Paul James. I used it some time ago and it worked for me.

HTTP Authentication with HTML Forms

[...] XMLHTTPRequest, it can submit the correct HTTP auth headers for us. Rather than adjusting the URL the form submits to, we can use XMLHTTPRequest to do a request before the form submits supplying the entered username and password.

This will set up the browser with the HTTP auth credentials so it'll also send them with our actual form submission login request.

splattne
  • 102,760
  • 52
  • 202
  • 249
  • 2
    More than what I was looking for, but looks like a very nice way to replace the browser's default login dialog. – system PAUSE Jan 29 '09 at 16:17
  • 3
    I tried this and it works but I get this in Chrome console: Subresource requests whose URLs contain embedded credentials (e.g. `https://user:pass@host/`) are deprecated, and will be blocked in M59, around June 2017. See https://www.chromestatus.com/feature/5669008342777856 for more details. Are there any other methods? – Paintoshi Apr 26 '17 at 11:02