PDA

Click to See Complete Forum and Search --> : HTTP Authentication


Dillinger4
Feb 26th, 2004, 12:38 PM
Does anyone know how i can implement HTTP Authentication on a site? java.net.url has a method named setDefault(Authenticator a) so i assume that i have to create a custom subclass extending java.net.Authenticator. From what i have read i have to provide implementation for the requestPasswordAuthentication(InetAddress address, int port, String protocol, String prompt, String scheme) method. The docs say that when the url class needs a user name and password, it will ask the class that was passed in to setDefault() for it using the above method. The docs go on to say that the another method that must be overridden is PasswordAuthentication getPasswordAuthentication(). Then we have the PasswordAuthentication class which has it's constructor as PasswordAuthentication(String username, char[] password).

So how do i piece all of this togther?

CornedBee
Feb 26th, 2004, 05:41 PM
Well, here's an example. When authentication is needed, you want to popup a dialog like web browsers do.

You therefore derive a class from Authenticator.

import java.util.*;
import java.net.*;

import javax.swing.*;

public class TypicalAuthenticator extends Authenticator
{
HashMap currentLogins = new HashMap();

/** Gives the authentication info to the URL connection. */
protected PasswordAuthentication getPasswordAuthentication() {
Object o = currentLogins.get(getRequestingSite());
if(o == null) {
o = askForPassword();
currentLogins.add(getRequestingSite(), o);
}
return (PasswordAuthentication)o;
}

/** Retrieves info from the user. */
private PasswordAuthentication askForPassword() {
// Show some nice dialog with two inputs here.
// I'll just use two JOptionPane:input dialogs.
String user = JOptionPane.showInputDialog("Please enter a username for:\n" +
getRequestingPrompt());
String pass = JOptionPane.showInputDialog("Please enter the password:");
return new PasswordAuthentication(user, pass.toCharArray());
}
}
The rest is easy. :)

The example should be fully functional, but it doesn't offer escape routes, password hiding or any error checking. And it is untested.