开发者

getRequestProperty("Authorization") always returns null

开发者 https://www.devze.com 2022-12-31 08:15 出处:网络
I am trying to read the authorization header for an HTTP request (because I need to add something to it), but I always get null for t开发者_运维百科he header value. Other headers work fine.

I am trying to read the authorization header for an HTTP request (because I need to add something to it), but I always get null for t开发者_运维百科he header value. Other headers work fine.

public void testAuth() throws MalformedURLException, IOException{
    URLConnection request = new URL("http://google.com").openConnection();
    request.setRequestProperty("Authorization", "MyHeader");
    request.setRequestProperty("Stackoverflow", "anotherHeader");
    // works fine
    assertEquals("anotherHeader", request.getRequestProperty("Stackoverflow"));
    // Auth header returns null
    assertEquals("MyHeader", request.getRequestProperty("Authorization"));
}

Am I doing something wrong? Is this a "security" feature? Is there a way to make this work with URLConnection, or do I need to use another HTTP client library?


Apparently, it's a security "feature". The URLConnection is actually an instance of sun.net.www.protocol.http.HttpURLConnection. It defines getRequestProperty as:

    public String getRequestProperty (String key) {
        // don't return headers containing security sensitive information
        if (key != null) {
            for (int i=0; i < EXCLUDE_HEADERS.length; i++) {
                if (key.equalsIgnoreCase(EXCLUDE_HEADERS[i])) {
                    return null;
                }
            }
        }
        return requests.findValue(key);
    }

The EXCLUDE_HEADERS array is defined as:

   // the following http request headers should NOT have their values
   // returned for security reasons.
   private static final String[] EXCLUDE_HEADERS = {
           "Proxy-Authorization",
           "Authorization"
   };


I am not happy about the extra dependencies, but following the suggestion to switch to Commons Http solved the immediate problem for me.

I'd still like to know what the problem was with my original code.


As Devon's answer correctly states: it's not a bug, it's a "security" feature

0

精彩评论

暂无评论...
验证码 换一张
取 消