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 sun.misc.BASE64Decoder;

import com.java2novice.model.Order;

public class OrderInventoryService {

	public Object getUserById(@PathParam("orderId") Integer orderId, 
							@HeaderParam("authorization") String authString){
			return "{\"error\":\"User not authenticated\"}";
		Order ord = new Order();
		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
		decodedAuth = new String(bytes);
		 * 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


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)
		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 

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 package
  21. Java client for restful web service using Jersey API
  22. Java restful webservices with HTTP basic authentication.
Knowledge Centre
When to use LinkedList or ArrayList?
Accessing elements are faster with ArrayList, because it is index based. But accessing is difficult with LinkedList. It is slow access. This is to access any element, you need to navigate through the elements one by one. But insertion and deletion is much faster with LinkedList, because if you know the node, just change the pointers before or after nodes. Insertion and deletion is slow with ArrayList, this is because, during these operations ArrayList need to adjust the indexes according to deletion or insetion if you are performing on middle indexes. Means, an ArrayList having 10 elements, if you are inserting at index 5, then you need to shift the indexes above 5 to one more.
Famous Quotations
Never argue with a fool, onlookers may not be able to tell the difference.
-- Mark Twain

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected].

Most Visited Pages

Other Interesting Sites

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