Java Reference
In-Depth Information
CHAPTER 4
Password Authentication
Hardcoding passwords in source code, as Examples
2-1
and
3-1
do, is a very bad idea
to say the least. If a password is required, you should ask the user for it at runtime.
Furthermore, when the user types the password, it should not be displayed on the screen.
Ideally, it should not even be transmitted in clear text across the network, although in
fact many current clients and servers do exactly that.
When you start a mail session, the JavaMail API allows you to provide a
jav
ax.mail.Authenticator
object that it can use to get the username and password.
Au
thenticator
is an abstract class:
public
abstract
class
Authenticator
extends
Object
When the provider needs to know a username or password, it calls back to the
getPass
wordAuthentication()
method in a user-defined subclass of
Authenticator
. This re‐
turns a
PasswordAuthentication
object containing this information:
protected
PasswordAuthentication
getPasswordAuthentication
()
These two classes are almost exactly the same as the
java.net.Authen
ticator
and
java.net.PasswordAuthentication
classes. Everything
you know about
java.net.Authenticator
and
java.net.PasswordAu
thentication
is true of
javax.mail.Authenticator
and
jav
ax.mail.PasswordAuthentication
. The only thing you have to watch
out for is that if you import both
java.net.*
and
javax.mail.*
in a
class, your source code will have to use fully qualified names like
java.net.Authenticator
instead of short names like
Authenticator
.
To add runtime password authentication to your programs, subclass
Authenticator
and override
getPasswordAuthentication()
with a method that knows how to