2

I have a Tomcat server that only serves static files(html, css, js). When the request comes in it gets intercepted by a proxy server. Proxy server authenticates the user and adds a userId field to the header and forwards it my Tomcat server.

How can I access userId that has been stored in the header from javascript?

Thank you

gumenimeda
  • 815
  • 7
  • 15
  • 43
  • Javascript is executed on the client side. Unless you send back the userid as part of the data from Tomcat, you cannot do this. – thatidiotguy Jun 04 '14 at 18:02
  • http://stackoverflow.com/questions/220231/accessing-the-web-pages-http-headers-in-javascript?rq=1 Dupe, I think – miguel-svq Jun 04 '14 at 18:02
  • what if I make a request from this page and then get a header as part of response? I can do that? – gumenimeda Jun 04 '14 at 20:19

2 Answers2

5

You can't, BUT...

If such header is send to the browser you could make an ajax request and get that value from it.

This little javascript could be useful in your case. Watch out, use it with caution and sanitize or change the URL depending on your needs, this is just a "concept", not a copy-paste solution for every case. In many other cases this is not a valid solution, cause it is not the header of the loaded document, but another request. Anyway the server, content-type, etc can be use quite safely.

xmlhttp = new XMLHttpRequest();
xmlhttp.open("HEAD", document.URL ,true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
  console.log(xmlhttp.getAllResponseHeaders());
  }
}
xmlhttp.send();

EDIT: Ooops, seem already anwser that part also... Accessing the web page's HTTP Headers in JavaScript Didn't read it all.

Community
  • 1
  • 1
miguel-svq
  • 2,136
  • 9
  • 11
1

Use below script for access userId

var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
headers = req.getAllResponseHeaders().split("\n")
     .map(x=>x.split(/: */,2))
     .filter(x=>x[0])
     .reduce((ac, x)=>{ac[x[0]] = x[1];return ac;}, {});

console.log(headers.userId);
Pankaj Chauhan
  • 1,623
  • 14
  • 12