MrBool
You must be logged in to give feedback. Click here to login
[Close]

You must be logged to download.

Click here to login

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Web Service Authentication using Java

In this article, you will see how we add the security elements to the JAX-WS service; build, package, and deploy the service; and then build and run the client application.

[close]

You didn't like the quality of this content?

Would you like to comment what you didn't like?

In the previous article about Java Web Service Programming, we saw how to write a simple web service using Java. In this article I shall guide you through authentication of web services using Java.

Imagine a scenario where you have developed a web service and published it on the server. Now everyone can access this. But you would want only specific registered people to access it, that is only authorized people can access it. One way to do this is by using authentication procedure in JAX-WS. This can be achieved by client providing the "username" and "password", attached in the SOAP request header and sending it to the server.

The server then parses SOAP document and fetches the "username" and "password" from header. The server then verifies that the "username" and "password" are valid by comparing them against a database (or any other preferred method) of authorized users.

Note: Assuming that the reader of this article has basic knowledge about SOAP and Web services

Step 1: Create a simple Java program (Service)

First, let us define the API to be exposed.

Listing 1: HelloWorld.java

package com.mrbool.ws;

public interface HelloWorld {
   String getHelloWorldMessage();
}

Implementation is as follows:

Listing 2: HelloWorldImpl.java

package com.mrbool.ws;

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

Step 2: Modify the Service as Web Service

Modify the service created in the previous section to Web service and also check for authentication of the user as show below:

The revised interface HelloWorld.java is as follows:

Listing 3: HelloWorld.java updated

package com.mrbool.ws;

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

Revised implementation HelloWorldImpl.java is as follows:

Listing 4: HelloWorldImpl.java updated

package com.mrbool.ws;

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.mrbool.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!";
		}
	}

} 

If you notice in the above code we get details like username and password from the request header. Check if the username is "Manisha" and password is "password", if true, then return a successful authentication message otherwise return the failure authentication message.

Step 3: Adding WS exposed code

Publish the web service locally by creating the Endpoint publisher and expose the service on the server.

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

This line here starts a lightweight http server endpoint that deploys your web service and starts accepting incoming requests.

The publish method takes two parameters:

  1. Endpoint URL String
  2. Implementer object, in this case the HelloWorld implementation class, which is exposed as a web service at the endpoint identified by the URL mentioned in the parameter above.

Listing 5: HelloWorldPublisher.java

 package com.mrbool.endpoint;

 import javax.xml.ws.Endpoint;
 import com.mrbool.ws.HelloWorldImpl;

 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 a Web Service Client

In the client code, put the "username" and "password" in the request header and send it for authentication. The comments on each step in the code explains the client code.

The Client file, HelloWorldClient.java is as follows:

Listing 6: HelloWorldClient.java

package com.mrbool.client;

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;

import com.mrbool.ws.HelloWorld;

public class HelloWorldClient {
	private static final String WS_URL =
			"http://localhost:9000/ws/hello?wsdl";

	public static void main(String[] args) throws Exception {
		URL url = new URL(WS_URL);
		QName qname = new QName(
			"http://ws.mrbool.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 and Run

Compile the service and publisher files and execute them. Create a batch file.

compileandrun.bat

dir /b /s *.java >> files.txt
javac @files.txt
java com.mrbool.endpoint.HelloWorldPublisher

Place the batch files in the directory com.mrbool.

  • The first line in the batch lists all the java files under subfolders and writes the full path of files to "files.txt".
  • Second line issues the compile command to all the java files listed in the file "files.txt"
  • Third line executes the HelloWorldPublisher class.

Execute the batch file and the output (System.Out present in the HelloWorldPublisher class) is as follows:

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

Step 6: Test WS Client

Write a batch file to test the client

executeClient.bat

java com.mrbool.client.HelloWorldClient
PAUSE

Execute the executeClient.bat and the output is follows:

Hello Manisha to world of Jax WS - Valid User! 

Step 7: Generate the WSDL

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

Conclusion

In this article we saw how to provide a basic authentication for a web service Using Java programming language. That’s it for now.



Freelance technical writer by profession with hands on experience in Java/J2EE technologies.

What did you think of this post?
Services
Know how to keep MrBool Online
SUPPORT US
SUPPORT US
With your help, we can keep providing free content and helping you to be a better professional
support us
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually � in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits � in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login