views:

464

answers:

4

Part of our website is protected with .htaccess style password protection. When you try to access this area of the website the web browser pops up a dialog asking for your username and password.

I need to access this programatically (eg with an ajax call). How does the server tell me it needs a password and how do I supply it?

+12  A: 

Basic HTTP authentication:

http://coderseye.com/2007/how-to-do-http-basic-auth-in-ajax.html

mcandre
Could be Digest authentication, also. The basic technique is the same, but the details of what the response looks like are different.
S.Lott
+1  A: 

In general, http://user:[email protected]

But there are some obvious security shortcomings with that.

A more complete solution may be to set a Session variable after a user is authenticated.

Make the AJAX post to a script that checks authentication. If authenticated, use CURL to fetch the results using a pre-defined authorized account.

This allows you to re-use basic apache auth but prevents any passwords from being written in the DOM.

rooskie
The site in question is https, which I assume will reduce the security issues. Is the URL passed to the server encrypted in an https session - I assume it is...?
rikh
better still httpS://user:[email protected]
KevinDTimm
The URL should be secure, but you're still writing the user/pass right in plain site as part of an href. Even if the u/p can't get sniped in transit, there's still some issues there.
rooskie
The URL is encrypted, only the host-name and port-number is transferred in plain text (http://answers.google.com/answers/threadview/id/758002.html). Also keep in mind that the syntax isn't supported in IE6 (http://support.microsoft.com/kb/834489), but what did you expect?
Ronald
+2  A: 

this is of course not ajax, but with wget client you can use --http-user and --http-password flags

Evgeny
+3  A: 

jQuery supports HTTP authentication with their ajax() method. Something like this should work:

jQuery.ajax({
    type: "GET",
    url: "foo.php",
    username: "foo",
    password: "bar"
});

Documentation on all jQuery.ajax() options can be found here: http://docs.jquery.com/Ajax/jQuery.ajax#options

Jon Mooring