JAX-WS Basic authentication

User Rating: 5 / 5

Star ActiveStar ActiveStar ActiveStar ActiveStar Active

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:




Authentication can be performed using a simple function:

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


Here’s the full code:

public class SecuredWSImpl implements SecuredWS {

 WebServiceContext wsctx;
 public void doSomething () {

 // 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 =============");
  else {
   throw new RuntimeException("Authentication failed! Wrong username / password!");


Related articles available on mastertheboss.com

JBoss web services

JAX-WS simplifies the development model for a web service endpoin

What is a Web Service One Way invocation?

JBoss recipe of the day

Asynchronous web services with JBoss WS

Developing rigorous and responsive web service client application

How to change the default Web Service deployment Port ?

JBoss recipe of the day

Using Axis Web Services with JBoss

Still not ready for JBoss WS ? if you don't have a JDK 1.5 compli

Invoking JBoss Web Services with Flex

Flex® is a free, open source framework for building highly in