Java Reference
In-Depth Information
@Override
public
void
actionPerformed
(
ActionEvent
event
)
{
passwordDialog
.
setVisible
(
false
);
}
}
public
PasswordAuthentication
getPasswordAuthentication
()
{
passwordDialog
.
setVisible
(
true
);
// getPassword() returns an array of chars for security reasons.
// We need to convert that to a String for
// the PasswordAuthentication() constructor.
String
password
=
new
String
(
passwordField
.
getPassword
());
String
username
=
usernameField
.
getText
();
// Erase the password in case this is used again.
// The provider should cache the password if necessary.
passwordField
.
setText
(
""
);
return
new
PasswordAuthentication
(
username
,
password
);
}
}
Most of this code is just for handling the GUI.
Figure 4-1
shows the rather simple dialog
box this produces.
Figure 4-1. An authentication dialog
Interestingly,
JPasswordField
takes more pains to be secure than
PasswordAuthenti
cation
does.
JPasswordField
stores passwords as an array of chars so that when you're
done with the password, you can overwrite it with nulls. This means the password exists
in memory for less time and the virtual memory system is less likely to swap the program
out to disk and leave the password there in clear text. However,
PasswordAuthentica
tion
stores passwords as strings, which are immutable and therefore are more likely to
be written to disk in a VM swap.
Modifying the POP client to support this style of authentication is straightforward, as
Example 4-2
demonstrates. We replace the hardcoded username and password with
nulls and pass an instance of
MailAuthenticator
as the second argument to
con
nect()
. The only other change is that we call
System.exit()
at the end of the
main()
method, since the program will no longer exit when the
main()
method returns once
the event dispatch thread has been started.