JAX-WS and BASIC authentication, when user names and passwords are in a database

ahoge picture ahoge · Oct 23, 2009 · Viewed 100.6k times · Source

I'm new to JAX-WS and there's a thing which I don't understand.

There's a ton of tutorials available on how to set up JAX-WS security, but in pretty much all cases BindingProvider.USERNAME_PROPERTY and BindingProvider.PASSWORD_PROPERTY are stored in some .xml file(depending on the container I believe) - they are "hardcoded" that is. And that's what I don't get. How can I authenticate a web service client by comparing BindingProvider.USERNAME_PROPERTY and BindingProvider.PASSWORD_PROPERTY with a user name and password that's in a database? I tried setting BindingProvider.USERNAME_PROPERTY and BindingProvider.PASSWORD_PROPERTY on the client side like this:

    ShopingCartService scs = new ShopingCartService(wsdlURL, name);
    ShopingCart sc = scs.getShopingCartPort();
    Map<String, Object> requestContext = ((BindingProvider)sc).getRequestContext();
    requestContext.put(BindingProvider.USERNAME_PROPERTY, userName);
    requestContext.put(BindingProvider.PASSWORD_PROPERTY, password);
    sc.someFunctionCall();

And then, on the server side retrieving like this:

@Resource
WebServiceContext wsContext;

@WebMethod
public void someFunctionCall() {
    MessageContext mc = wsContext.getMessageContext();
    mc.get(BindingProvider.USERNAME_PROPERTY);
    mc.get(BindingProvider.PASSWORD_PROPERTY);
}

But I always get null, I didn't set up anything in xml, web service works just fine, except I can't get those variables :(

I'm running both on java 1.6, tomcat 6 and JAX-WS.

Any help with authenticating users with passwords from a database is greatly appreciated, Thanks.

Answer

mkyong picture mkyong · Dec 16, 2010

I think you are looking for JAX-WS authentication in application level, not HTTP basic in server level. See following complete example :

Application Authentication with JAX-WS

On the web service client site, just put your “username” and “password” into request header.

Map<String, Object> req_ctx = ((BindingProvider)port).getRequestContext();
req_ctx.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, WS_URL);

Map<String, List<String>> headers = new HashMap<String, List<String>>();
headers.put("Username", Collections.singletonList("someUser"));
headers.put("Password", Collections.singletonList("somePass"));
req_ctx.put(MessageContext.HTTP_REQUEST_HEADERS, headers);

On the web service server site, get the request header parameters via WebServiceContext.

@Resource
WebServiceContext wsctx;

@WebMethod
public String method() {
    MessageContext mctx = wsctx.getMessageContext();

    Map http_headers = (Map) mctx.get(MessageContext.HTTP_REQUEST_HEADERS);
    List userList = (List) http_headers.get("Username");
    List passList = (List) http_headers.get("Password");
    //...