JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Publish Your Article Here

Java restful webservices with HTTP basic authentication.


In the context of a HTTP transaction, basic access authentication is a method for an HTTP user agent to provide a user name and password when making a request.

HTTP Basic authentication implementation is the simplest technique for enforcing access controls to web resources because it doesn't require cookies, session identifier and login pages. Rather, HTTP Basic authentication uses static, standard HTTP headers which means that no handshakes have to be done in anticipation.

When the user agent wants to send the server authentication credentials it may use the Authorization header. The Authorization header is constructed as follows:

1) Username and password are combined into a string "username:password"
2) The resulting string is then encoded using Base64 encoding
3) The authorization method and a space i.e. "Basic " is then put before the encoded string.

For example, if the user agent uses 'Aladdin' as the username and 'open sesame' as the password then the header is formed as follows:

Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

Java Rest Service method with GET Request which supports HTTP basic authentication

package com.java2novice.restful;

import java.io.IOException;

import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import sun.misc.BASE64Decoder;

import com.java2novice.model.Order;

@Path("/order-inventory")
public class OrderInventoryService {

	@GET
	@Path("/order/{orderId}")
	@Produces(MediaType.APPLICATION_JSON)
	public Object getUserById(@PathParam("orderId") Integer orderId, 
							@HeaderParam("authorization") String authString){
		
		if(!isUserAuthenticated(authString)){
			return "{\"error\":\"User not authenticated\"}";
		}
		Order ord = new Order();
		ord.setCustmer("Java2Novice");
		ord.setAddress("Bangalore");
		ord.setAmount("$2000");
		return ord;
	}
	
	private boolean isUserAuthenticated(String authString){
		
		String decodedAuth = "";
		// Header is in the format "Basic 5tyc0uiDat4"
		// We need to extract data before decoding it back to original string
		String[] authParts = authString.split("\\s+");
		String authInfo = authParts[1];
		// Decode the data back to original string
		byte[] bytes = null;
		try {
			bytes = new BASE64Decoder().decodeBuffer(authInfo);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		decodedAuth = new String(bytes);
		System.out.println(decodedAuth);
		
		/**
		 * here you include your logic to validate user authentication.
		 * it can be using ldap, or token exchange mechanism or your 
		 * custom authentication mechanism.
		 */
		// your validation code goes here....
		
		return true;
	}
}

Java Client for GET Request using Jersey API with HTTP basic authentication

package com.java2novice.rest.client;

import sun.misc.BASE64Encoder;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class JersyGetClient {

	public static void main(String a[]){
		
		String url = "http://localhost:8080/RestfulWebServices/order-inventory/order/1016";
		String name = "java2novice";
		String password = "Simple4u!";
		String authString = name + ":" + password;
		String authStringEnc = new BASE64Encoder().encode(authString.getBytes());
		System.out.println("Base64 encoded auth string: " + authStringEnc);
		Client restClient = Client.create();
		WebResource webResource = restClient.resource(url);
		ClientResponse resp = webResource.accept("application/json")
										 .header("Authorization", "Basic " + authStringEnc)
										 .get(ClientResponse.class);
		if(resp.getStatus() != 200){
			System.err.println("Unable to connect to the server");
		}
		String output = resp.getEntity(String.class);
		System.out.println("response: "+output);
	}
}
<< Previous Program 
blog comments powered by Disqus

Restful Web Services Examples

  1. Restful web services using RESTEasy hello world example.
  2. Restful web services using Jersey hello world example.
  3. JAX-RS @Path annotation example
  4. JAX-RS @Path annotation with regular expression match example
  5. JAX-RS @PathParam annotation example
  6. JAX-RS @QueryParam and @DefaultValue annotations example
  7. JAX-RS @MatrixParam annotation example
  8. How to read multiple values of a query paramter in JAX-RS restful web services?
  9. How to pass header parameters as method inputs in JAX-RS restful web services?
  10. How to read header parameters in JAX-RS restful web services?
  11. JAX-RS @FormParam annotation example
  12. How to upload file using Jersey restful web services?
  13. How to download file using java restful web services?
  14. XML based Restful web service with RESTEasy and JAXB.
  15. XML based Restful web service with Jersey and JAXB.
  16. Json based Restful web service with RESTEasy, Jettison and JAXB
  17. Json based Restful web service with RESTEasy and Jackson
  18. Json based Restful web service with Jersey and Jackson
  19. How to input json request with Jersey and Jackson?
  20. Java client for restful web service using java.net package
  21. Java client for restful web service using Jersey API
  22. Java restful webservices with HTTP basic authentication.
Knowledge Centre
Can interface be final?
No. We can not instantiate interfaces, so in order to make interfaces useful we must create subclasses. The final keyword makes a class unable to be extended.
Famous Quotations
The very best thing you can do for the whole world is to make the most of yourself.
-- Wallace Wattles

About Author

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2017 by Nataraja Gootooru. All Rights Reserved.