Thursday, April 25, 2013

JAX-RS Tip of the Day: How Do I Read the Authorization Header?

I was looking for a simple method to read the HttpHeaders to determine the username and password for a request. I didn't find a quick answer so I wrote a simple utility method that will return the Base 64 decoded values from the authorization header.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
 * This method examines the request {@link HttpHeaders} for an authorization
 * header. If the header is found, this will return the base64 decoded
 * values of the username, and password.
 *
 * @param headers The headers to be examined.
 * @return an array containing the username and password, or {@code null} if
 * the authorization header was not present.
 */
public String[] getAuthorization(HttpHeaders headers) {
    String[] decoded = null;
    List<String> header = headers.getRequestHeader("authorization");
    if (header != null) {
        String authorization = header.get(0);
        // There is a space between "Basic" and the Base 64 encoded string.
        authorization = authorization.substring("Basic ".length());
        decoded = Base64.base64Decode(authorization).split(":");
    }
    return decoded;
}

0 comments :

Popular Posts