JAVA Tutorials

How to apply Username/password Security in Web Service?

Basic authentication is a method to provide a username and password security while making a request.

Let us imagine that you have developed a web service and published it on a server. Now everyone can access it, but you want to provide access to some specified registered users. This can be done by using an authentication procedure in JAX-WS. It can be achieved by providing the username and password security, attached in the SOAP request header, and sending it to the server. The server will then parse the SOAP document and fetches the username and password from the header. The server will then verify that the username and password are valid by searching them into the database of registered users.

Let us create a simple Authentication program:

Step 1: Create a simple java service.

HelloWorld.java

public interface HelloWorld {
   String getHelloWorldMessage();
}

HelloWorldImpl.java

public class HelloWorldImpl  implements HelloWorld  {
@Override
public String getHelloWorldMessage(String myName){
return("Hello "+myName+" to JAX WS world");
}
}

Step 2: Modify the service to Web service and check for authentication of the user.

HelloWorld.java updated

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
@WebService
@SOAPBinding(style = Style.RPC)
public interface HelloWorld {
@WebMethod
String getHelloWorldMessage();

At the Web Service server side, get the request header parameters via WebServiceContext

HelloWorldImpl.java updated

import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.jws.WebService;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;
@WebService(endpointInterface = "com.ws.HelloWorld")
public class HelloWorldImpl implements HelloWorld {
@Resource
WebServiceContext wsctx;
@Override
public String getHelloWorldMessage() {
MessageContext mctx = wsctx.getMessageContext();
// Use the request headers to get the details
Map http_headers =
(Map) mctx.get(
MessageContext.HTTP_REQUEST_HEADERS);
List<String> userList = (List) http_headers.get("Username");
List<String> passList = (List) http_headers.get("Password");
String username = "";
String password = "";
if (userList != null) {
username = userList.get(0);
}
if (passList != null) {
password = passList.get(0);
}
if (username.equals("Manisha")
&&
password.equals("password")) {
return "Hello "
+ username +
" to world of Jax WS - Valid User!";
} else {
return " User No Valid!";
}
}
}

The above code will check whether the username is Manisha and password is password or not. If the condition met true, it will return a successful authentication message; otherwise, it will return the failed authentication message.

Step 3: Add the WS exposed code.

Publish the web service locally and expose it to the server.

Endpoint.publish(“http://localhost:9000/ws/hello”, new HelloWorldImpl());

The above line will deploy the web service and start accepting incoming requests.

The publish method will take two parameters:

  1. Endpoint URL String
  2. Implementer object

HelloWorldPublisher.java

import javax.xml.ws.Endpoint;
 public class HelloWorldPublisher {
  public static void main(String[] args){
  Endpoint.publish(
  "http://localhost:9000/ws/hello", new HelloWorldImpl());
  System.out.println(
  "\nWeb service published @ http://localhost:9000/ws/hello");
System.out.println("You may call the web service now");
  }
 }

Step 4: Create the Web Service Client.

HelloWorldClient.java

import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Service;
import javax.xml.ws.handler.MessageContext;
public class HelloWorldClient {
private static final String WS_URL =
"http://localhost:9000/ws/hello?wsdl";
public static void main(String[] arg) throws Exception {
URL url = new URL(WS_URL);
QName qname = new QName(
"http://ws.example.com/",
"HelloWorldImplService");
Service service = Service.create(url, qname);
HelloWorld hello = service.getPort(HelloWorld.class);
// The BindingProvider interface provides
//access to the protocol binding and
// to the associated context objects
//for request and response message processing.
BindingProvider provider = (BindingProvider) hello;
Map<String, Object> req_ctx = provider.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("Manisha"));
headers.put("Password",
Collections.singletonList("password"));
req_ctx.put(MessageContext.HTTP_REQUEST_HEADERS, headers);
System.out.println(hello.getHelloWorldMessage());
}
}

Step 5: Compile the service and Run by executing the batch file.

compileandrun.bat

dir /b /s *.java >> files.txt

javac @files.txt

java com.examole.endpoint.HelloWorldPublisher

  • The first line in the batch contains all the java files under subfolders and writes the full path of files to “files.txt.”
  • The second line issues the compile command to all the java files listed in the file “files.txt.”
  • The third line executes the HelloWorldPublisher class.

After executing the batch file output will be:

Web service published @ http://localhost:9000/ws/hello You may call the web service now

Step 6: Test the WS Client by executing the below batch file.

executeClient.bat

java com.example.client.HelloWorldClient

PAUSE

After executing the above batch file, output will be:

Hello Manisha to world of Jax WS – Valid User! 

Step 7: Generate WSDL

Test the web service by accessing the WSDL (Web Service Definition Language) document generator using URL “http://localhost:9000/ws/hello?wsdl”. This describes the detail of the exposed APIs of the Web Service. The client can be built in any programming language, as it is language-neutral.

Facebook Comments
Tags

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back to top button
Close
Close