JAX-WS Basic authentication


Another option is using the @WebServiceContext to access the Authorization parameter contained in the Header. This is a portable solution although it needs a bit more of work to decode the credentials to Base64 to plain text.

 

 

This requires Apache commons-codec libraries. You can download them here:

 

http://commons.apache.org/codec/

 

Authentication can be performed using a simple function:


byte[] buf = Base64.decodeBase64(userpass.getBytes());

 

Here’s the full code:

@WebService
public class SecuredWSImpl implements SecuredWS {

 @Resource
 WebServiceContext wsctx;
 
 
 public void doSomething () {

 doAuthentication();
 
 // Execute WS business logic
 }
 
 private void doAuthentication() {

 

 

 MessageContext mctx = wsctx.getMessageContext();
 Map http_headers = (Map) mctx.get(MessageContext.HTTP_REQUEST_HEADERS);
 
  ArrayList list = (ArrayList) http_headers.get("Authorization");
  if (list == null || list.size() == 0) {
    throw new RuntimeException("Authentication failed! This WS needs BASIC Authentication!");
 }
 
  String userpass = (String) list.get(0);
  userpass = userpass.substring(5);
  byte[] buf = Base64.decodeBase64(userpass.getBytes());
  String credentials = new String(buf);
 
  String username = null;
  String password = null;
  int p = credentials.indexOf(":");
  if (p > -1) {
   username = credentials.substring(0, p);
   password = credentials.substring(p+1);
  }   
  else {
   throw new RuntimeException("There was an error while decoding the Authentication!");
  }
  // This should be changed to a DB / Ldap authentication check 
  if (username.equals("admin") && password.equals("admin")) { 
  System.out.println("============== Authentication OK =============");
  return;
  }
  else {
   throw new RuntimeException("Authentication failed! Wrong username / password!");
  }
 
 }
 
}


Advertisement