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
ServletOuptputStream Vs PrintWriter
ServletOutputStream: ServletResponse.getOutputStream() returns a ServletOutputStream suitable for writing binary data in the response. The servlet container does not encode the binary data, it sends the raw data as it is.

PrintWriter: ServletResponse.getWriter() returns PrintWriter object which sends character text to the client. The PrintWriter uses the character encoding returned by getCharacterEncoding(). If the response's character encoding has not been specified then it does default character encoding.
Famous Quotations
Before you go and criticize the younger generation, just remember who raised them.
-- Unknown Author

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.