Handling Authentication Data

Listing 1. If we want our handler to gather the username and password, we can use this code to get the user name and password form the system input stream and pass those values to whichever login module is calling us.

class MyCallbackHandler implements CallbackHandler
{
  public void handle(Callback[] callbacks)
    throws IOException, UnsupportedCallbackException
  {
    BufferedReader br = new BufferedReader(
                    new InputStreamReader(System.in));

    for (int i = 0; i < callbacks.length; i++)
    {
      if (callbacks[i] instanceof NameCallback)
      {
        System.err.println(((NameCallback) 
                          callbacks[i]).getPrompt());
        String name = br.readLine();
        ((NameCallback) callbacks[i]).setName(name);
      }
      else if (
        callbacks[i] instanceof PasswordCallback)
        {
        System.err.println(((PasswordCallback)
                        callbacks[i]).getPrompt());

        String pwd = br.readLine();
        ((PasswordCallback) callbacks[i]).
          setPassword(pwd.toCharArray());
      }
    }
  }
}