3

I need to authenticate against a proxy server, and after the first HTTP request the I need to parse the proxy-authenticate header string to get the relevant values.

The response headers look something like this,

{ 'content-type': 'text/plain',
  'proxy-authenticate': 'Digest realm="zippy", qop="auth",nonce="c1e1c76b5df5a8cdc921b48d6a7b5493", algorithm="MD5", stale="false"',
   date: 'Thu, 21 Apr 2016 00:19:28 GMT',
   connection: 'close',
  'transfer-encoding': 'chunked' }

I want to extract the proxy-authenticate parameters (i.e. realm, qop, etc.), from the string.

It seems like there must be some super simple way to do this, but I'm just not finding it.

Duncan Drennan
  • 871
  • 2
  • 9
  • 21
  • Is this an AJAX request? Please see [this question](http://stackoverflow.com/questions/1557602/jquery-and-ajax-response-header) and [this question](http://stackoverflow.com/questions/220231/accessing-the-web-pages-http-headers-in-javascript). – Kevin Page Apr 21 '16 at 00:36
  • Hi Kevin, no this is not AJAX. it is just a straight post from Node using the http library. – Duncan Drennan Apr 21 '16 at 14:00

1 Answers1

2

Simply extract your key from the JSON, and split the value by ,. Then again split each value of resulting array using =.

$(document).ready(function() {
  var data = {
    'content-type': 'text/plain',
    'proxy-authenticate': 'Digest realm="zippy", qop="auth",nonce="c1e1c76b5df5a8cdc921b48d6a7b5493", algorithm="MD5", stale="false"',
    date: 'Thu, 21 Apr 2016 00:19:28 GMT',
    connection: 'close',
    'transfer-encoding': 'chunked'
  };

  var header = data['proxy-authenticate'];
  var contents = header.split(',');

  var pairs = {};
  $.each(contents, function(index, value) {

    var pair = value.split('=');
    pairs[pair[0]] = pair[1];
  });

  $('div').html(JSON.stringify(pairs));
});

Here is a demo.

Rash
  • 7,677
  • 1
  • 53
  • 74
  • Unfortunately fails if one of the values contains a comma or equal signe. E.g. `realm="x,y"` or `nonce="abcdef=="`. And it further lists `" qop"` with leading space! – Joe Sep 30 '17 at 10:35
  • @Joe The input must be cleaned before trying to extract data from it. E.g. If your input can guarantee that each value is of format `{="",=""}` then instead of splitting on `,` you can split on `",` which will solve your comma inside a value problem. Of course if the value itself contains `",` then program will again fail. Any data before parsing needs to guarantee a format and based on the format the parser can be written. Let me know your thoughts. – Rash Sep 30 '17 at 15:28
  • @Joe The second problem of properties having multiple `=` cannot be solved easily. Imagine the property `abc=d=ef=g`. In this case no one knows which `=` is the delimeter, and hence this value can never be parsed correctly on its own. As I said, the input you are getting needs to follow a pattern or define a contract. Without that parsing would be hard. Let me know your thoughts. – Rash Sep 30 '17 at 15:31