Search code examples
angularjsbrowserhttp-headershttp-authentication

angular HTTP auth: not getting browser login prompt


In my angular app, i am trying to do basic HTTP auth.

I send the http get request from angular without any credentials initially, as i assume that when the backend sends a 401 status, the browser would ask me for credentials and would then resubmit the request on its own.

But the browser login prompt is never displayed. This is the error that i get:

angular.js:11756 GET http://localhost:8080/appName/rest/keys/Keys?batch=0&userName=Test 401 (Unauthorized)

These are the headers i get for response:

Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:origin, content-type, accept, authorization
Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS, HEAD
Access-Control-Allow-Origin:http://localhost:3001/
Content-Length:0
Date:Tue, 09 Aug 2016 14:53:26 GMT
Server:Apache-Coyote/1.1
WWW-Authenticate:Basic

I was hoping that the browser prompt would appear automatically when it encounters status 401, but it doesn't seem to be the case here. Am i missing something?

EDIT:

It does not work in Chrome and Firefox, but works in IE, IE displays a login prompt when i try to access the url, and works correctly with username and password, while Chrome directly gives a 401 error.

If i try to access the server url directly from address bar, then Chrome displays the login prompt and asks me for the credentials. Not sure, but can it be a CORS issue?


Solution

  • Ok, i was able to resolve the issue.

    The problem was indeed related to CORS, not in a direct way. Also, it was working on IE since IE does not respect CORS and will anyways let you access cross origin.

    Two things were missing:

    Initially i was sending (along with other headers) Access-Control-Allow-Origin : * from the server, for enabling CORS. Then i got to know this:

    Firefox and Chrome require exact domain specification in Access-Control-Allow-Origin header. For servers with authentication, these browsers do not allow "*" in this header. The Access-Control-Allow-Origin header must contain the value of the Origin header passed by the client.

    https://www.webdavsystem.com/ajax/programming/cross_origin_requests/

    And then there was an issue related to cross origin browser auth:

    By default, in cross-site XMLHttpRequest invocations, browsers will not send credentials. A specific flag has to be set on the XMLHttpRequest object when it is invoked.

    https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials

    This specific flag is withCredentials : true, which needs to be set with the xhr request. I managed to set it with my http request from the angular app, and voila it worked!