Thursday 31 May 2018

Java Arguments - Can you say "Doofus" ?

In the context of my ongoing voyage of discovery that is IBM API Connect, I need to pass Basic Authentication credentials BUT as an HTTP header.

Therefore, I need to generate a suitably encoded header, as per RFC 7235, where the user ID and password are Base64 encoded.


Whilst this is a useful online tool: -


I wanted a differently better way.

So I'm knocking up a Java class to calculate Authorization headers, using this: -


as source material.

Here's what I have: -

package com.ibm;

import java.util.Base64;

public class genAuthHeader
{
public static void main(String[] args)
{
String username = args[1];
String password = args[2];

System.out.println("Authorization header is " + buildBasicAuthorizationString(username,password));

}

public static
String buildBasicAuthorizationString(String username, String password)
{
    String credentials = username + ":" + password;
    return "Basic " + new String(Base64.getEncoder().encode(credentials.getBytes()));
}
}


Having created / compiled the class, using Eclipse, when I attempt to run it: -

java com.ibm.genAuthHeader user@foobar.com p455w0rd!

I get this: -

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at com.ibm.genAuthHeader.main(genAuthHeader.java:10)


Can anyone see where I went wrong ?

Yep ?

This is Java where array indices start at ZERO :-)

I changed my code: -

package com.ibm;

import java.util.Base64;

public class genAuthHeader
{
public static void main(String[] args)
{
String username = args[0];
String password = args[1];


System.out.println("Authorization header is " + buildBasicAuthorizationString(username,password));

}

public static
String buildBasicAuthorizationString(String username, String password)
{
    String credentials = username + ":" + password;
    return "Basic " + new String(Base64.getEncoder().encode(credentials.getBytes()));
}
}


and NOW it works: -

java com.ibm.genAuthHeader user@foobar.com p455w0rd!

Authorization header is Basic dXNlckBmb29iYXIuY29tOnA0NTV3MHJkIQ==


No comments:

Visual Studio Code - Wow 🙀

Why did I not know that I can merely hit [cmd] [p]  to bring up a search box allowing me to search my project e.g. a repo cloned from GitHub...