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.
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()));
}
}
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: -
I get this: -
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at com.ibm.genAuthHeader.main(genAuthHeader.java:10)
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()));
}
}
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: -
Authorization header is Basic dXNlckBmb29iYXIuY29tOnA0NTV3MHJkIQ==
No comments:
Post a Comment