Learning The "J"

Home » JAVA Learning » JAVA EE » HTTP Authentication » HTTP Basic access authentication

HTTP Basic access authentication


Basic access authentication is a method for a HTTP user agent to provide a user name and password when making a request.

HTTP Basic authentication implementation is one of the easiest ways to secure web pages because it doesn’t require cookies, session handling, or the development of login pages. Rather, HTTP Basic authentication uses static headers which means that no handshakes have to be done in anticipation. Although the scheme is easily implemented, it relies on the assumption that the connection between the client and server computers is secure and can be trusted. Specifically, if SSL/TLS is not used, then the credentials are passed as plaintext and could be intercepted.

Server side Protocol

When the server wants the user agent to authenticate itself towards the server, it can send a request for authentication.
This request should be sent using the HTTP 401 Not Authorized response code containing a WWW-Authenticate HTTP header.

The WWW-Authenticate header for basic authentication (used most often) is constructed as following:

WWW-Authenticate: Basic realm=”insert realm”

Client side Protocol

When the user agent wants to send the server authentication credentials it may use the Authorization header.

The Authorization header is constructed as follows:

Username and password are combined into a string “username:password”
The resulting string literal is then encoded using Base64
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==

Here is a full working code in context of Restfull Web Services

//Client Side Script

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.commons.codec.binary.Base64.*;

public class HttpBasicAuth {

    public static void main(String[] args) {

        try {
            URL url = new URL ("");
            //String encoding = Base64Encoder.encode ("test1:test1");
            String encoding = org.apache.commons.codec.binary.Base64.encodeBase64String(

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty  ("Authorization", "Basic " + encoding);
            InputStream content = (InputStream)connection.getInputStream();
            BufferedReader in   = 
                new BufferedReader (new InputStreamReader (content));
            String line;
            while ((line = in.readLine()) != null) {
        } catch(Exception e) {


//Server Side Script

    public javax.ws.rs.core.Response getLogin(
            @Context HttpServletRequest req, @Context HttpServletResponse res) {
        try {            
            String pathInfo = req.getPathInfo();
            String header = req.getHeader("Authorization");
            //always wise to assert your assumptions
            assert header.substring(0, 6).equals("Basic ");
            String basicAuthEncoded = header.substring(6);
            String basicAuthAsString = new String(new Base64().decode(basicAuthEncoded.getBytes()));
            StringTokenizer tkn=new StringTokenizer(basicAuthAsString, ":");

            System.out.println(" tkn.nextToken() "+ tkn.nextToken());
            System.out.println(" tkn.nextToken() "+ tkn.nextToken());

            return Response.status(200).entity("success").build();

        } catch (NullPointerException npex) {
            ResponseBuilder rb = Response.status(401);
            rb = rb.tag("Authorization Required");
            return rb.build();

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Start here

%d bloggers like this: