Thursday, April 25, 2013

JSF Tip of the Day: Reading Authorization Header in JSF

After I did the JAX-RS Tip of the Day today, I wondered about reading the authorization header from JSF. The technique is the same as the JAX-RS version, but the methods are different depending on what is available to the JSF application. The JAX-RS Base64 class is not part of the web profile in Java EE 6. It will be part of Java EE 7 so you could use it. I chose to add the comments in the code below, but decided that I would use the com.sun.misc.Base64Decoder which is currently available in Java SE 6 and 7.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
  * This method examines the request headers for an authorization header. If
  * the header is found, this will return the base64 decoded values of the
  * username, and password.  
  *
  * @param facesContext The context to get the request headers from.  
  * @return an array containing the username and password, or {@code null}.  
  * @throws IOException if the authorization header can not be parsed.  
  */
 public String[] getAuthorization(final FacesContext facesContext) throws IOException {
     String[] decoded = null;
     ExternalContext ec = facesContext.getExternalContext();
     Map<String, String> map = ec.getRequestHeaderMap();
     String authorization = map.get("authorization");
 
     if (authorization != null && !authorization.isEmpty()) {
         // There is a space between "Basic" and the Base 64 encoded string.
         authorization = authorization.substring("Basic ".length());
         /*
          * This would work if JAX-RS (Jersey) was available, but it is not part of
          * Web Profile in EE 6, but will work in EE 7 since JAX-RS 2.0
          * is part of the profile.
          */
         // decoded = Base64.base64Decode(authorization).split(":");
 
         /*
          * This mechanism relies on sun.misc.BASE64Decoder that is an internal
          * proprietary API and may be removed in a future release.
          */
         // decoded = new String(new BASE64Decoder().decodeBuffer(authorization)).split(":");
 
         /*
          * This method uses a class from the Java API for XML Binding (JAXB) to parse. This is
          * available in Java EE 5 and 6.
          */
         decoded = new String(DatatypeConverter.parseBase64Binary(authorization), "UTF-8").split(":");
     }
     return decoded;
 }
UPDATE: I got a suggestion on Google+ from +Thomas Darimont who mentioned using DatatypeConverter.parseBase64Binary() from the Java API for XML Binding (JAXB). I confirmed that it is available in Java EE 5 and 6. It is also in the Web Profile in Java EE 6.

0 comments :

Popular Posts