user1544337
user1544337

Reputation:

Force showing the browser's HTTP authentication dialog

There are already several questions that ask for suppressing the browser's HTTP authentication dialog, and they seem to suggest that this dialog automatically appears when the response code is 401 and the WWW-Authenticate header is present in a response.

I'm building a web application that calls a RESTful API using Ajax, which is protected with basic HTTP authentication. I'm working on both the web app and the API.

The default behaviour is to, when authentication is required but not present, simply give an error

{"error":"Authentication required"}

with a 404 status. However, I would like to create one endpoint, /user/login, which returns the 401 code and a WWW-Authenticate header when there is no valid Authorization header present in the request. I know this isn't exactly RESTful, but it should work.

I have now implemented this and when I open the endpoint in my browser it works fine: the browser's dialog shows. However, when I request the endpoint using Ajax, no dialog is shown (both Chromium and Firefox).

How do I force showing this dialog with an Ajax request, if at all possible?

The exact response is now:

HTTP/1.1 401 Unauthorized
Server: nginx/1.4.6 (Ubuntu)
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
X-Powered-By: PHP/5.5.9-1ubuntu4.9
Access-Control-Allow-Origin: http://my-url
Cache-Control: no-cache
Date: Thu, 07 May 2015 12:21:10 GMT
WWW-Authenticate: Basic realm="Please login"

Please login

Upvotes: 3

Views: 3576

Answers (2)

mahemoff
mahemoff

Reputation: 46409

Create a "Login" web page that requires basic auth and link to it. It can have a meta or JavaScript redirect back to your main application; the redirect will only be applied after the user has authenticated themselves.

You could alternatively just request username and password using JavaScript and send them with subsequent Ajax calls (see https://stackoverflow.com/a/9613117/18706).

Upvotes: 1

user1544337
user1544337

Reputation:

As a (temporary?) workaround, I'm now redirecting users to the API, which I give a redirect parameter to which the user is redirected back when authentication has succeeded.

Upvotes: 0

Related Questions