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.

2
  • 3
    What do you mean pure javascript? You're looking for a way to set cookies with javascript without the page reloading? Commented Jan 29, 2009 at 16:01
  • 4
    Basic Authentication does not use cookies but HTTP headers. Commented Apr 1, 2014 at 11:09

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

More than what I was looking for, but looks like a very nice way to replace the browser's default login dialog.
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 chromestatus.com/feature/5669008342777856 for more details. Are there any other methods?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.