Showing posts with label http basic authentication. Show all posts
Showing posts with label http basic authentication. Show all posts

Saturday, May 3, 2014

EJB 3 Web Service Implementation with HTTP Basic Authentication & Authhorization

Before run this sample you have to make neccasery realm configution in your EJB 3.0 compatible application server.


  1. First create a Stateless bean  as shown below:

@Stateless (mappedName = "TestSecureWebService")
@WebService (targetNamespace = "http://webservice.duman.ozay.com/", serviceName = "TestSecureWebService")
public class TestSecureWebService implements TestSecureWebServiceRemote {
@Resource
private WebServiceContext webServiceContext;


@Override
@RolesAllowed({"CallServiceAccessRight"})
@WebMethod(operationName = "sampleSecureServiceSorgula")
@WebResult(name = "TestSecureService")
public String secureServiceMethod(String name) {
 MessageContext messageContext = webServiceContext.getMessageContext();
 javax.servlet.http.HttpServletRequest httpRequest = (javax.servlet.http.HttpServletRequest) messageContext.get(MessageContext.SERVLET_REQUEST);
 String userName = httpRequest.getRemoteUser();


 return "http basic auth. web service method called by " + userName;
}

}
You can access httpRequest information (client ip, remoteuser etc.) by injecting WebServiceContext resource.

To test this service you can simply use SOAP UI passing the service credentials or write a web service client as  follows:

public class WSClientMain {

 public static void main(String[] args) {
 TestSecureWebService  service =new TestSecureWebService();
 TestSecureWebServicePort  port = service.getTestSecureWebServiceservicePort();
 Map<String, Object> rc = ((BindingProvider) port).getRequestContext();
 
 rc.put(BindingProvider.USERNAME_PROPERTY, "user1");
 rc.put(BindingProvider.PASSWORD_PROPERTY, "testuser");
 
 String result= port.secureServiceMethod("abc");
 
 System.err.println(result);
 
 }

}