2
votes

I try to do a POST request with HttpRequest (dart:html) to call a rest service secured with basic authentication.

HttpRequest request = new HttpRequest(); // create a new XHR
var url = "http://localhost:8082/xyz";
request.open("POST", url, async: false); // POST the data to the server

String username = "foo";
String password = "bar";
final auth = CryptoUtils.bytesToBase64(UTF8.encode("$username:$password"));

request.setRequestHeader('authorization',"Basic $auth");
request.setRequestHeader('content-type',"application/json");
request.setRequestHeader("accept", "application/json");
String jsonData = '{"language":"dart"}'; // etc...

request.send(jsonData);  //exception 401 Unauthorized


Before performing the POST call the OPTIONS call is performed (issued by dart:html) without the authorization header. This leads into an 401 Unauthorized response.

Request header:

Accept:*/*
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Access-Control-Request-Headers: authorization, content-type, accept
Access-Control-Request-Method: POST
Cache-Control: max-age=0
Connection: keep-alive
Host: localhost:8082
Origin: http://localhost:63342
Referer: http://localhost:63342/dart_client/test/all_test.html
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.0 (Dart) Safari/537.36

Reponse header:

Content-Length: 0
Date: Mon, 02 Feb 2015 23:33:58 GMT
Server: Jetty(9.2.7.v20150116)
WWW-Authenticate: basic realm="xyzrealm"


Is there a way to provide the authorization header to the OPTIONS call?

Any suggestions would be great. Thanks

1

1 Answers

2
votes

The OPTIONS request is made by the browser automatically and you can't modify that request. The server needs to allow the OPTIONS preflight request without authentication.

See http://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0 The user credentials are excluded.