LoginModule
LoginModule Implementation
LoginModule
Methods
LoginModule and
Application
LoginModule
LoginModule
Implementation
LoginModule JAR File and
Documents Available
The JavaTM Authentication and Authorization Service (JAAS) was introduced as an optional package to the JavaTM 2 SDK, Standard Edition (J2SDK), v 1.3. JAAS has now been integrated into the J2SDK, v 1.4.
JAAS provides Subject-based authorization on authenticated identities. This document focuses on the authentication aspect of JAAS, specifically the
LoginModuleinterface.Who Should Read This Document
This document is intended for experienced programmers who require the ability to write a
LoginModuleimplementing an authentication technology.Related Documentation
This document assumes you have already read the following:
It also discusses various classes and interfaces in the JAAS API. Please reference the javadocs for the JAAS API specification for more detailed information:
- javax.security.auth Package
- javax.security.auth.callback Package
- javax.security.auth.kerberos Package
- javax.security.auth.login Package
- javax.security.auth.spi Package
- javax.security.auth.x500 Package
- com.sun.security.auth Package
- com.sun.security.auth.callback Package
- com.sun.security.auth.login Package
- com.sun.security.auth.module Package
The following tutorials for JAAS authentication and authorization can be run by everyone:
Similar tutorials for JAAS authentication and authorization, but which demonstrate the use of a Kerberos LoginModule and thus which require a Kerberos installation, can be found at
These two tutorials are a part of the Java GSS-API and JAAS sequence of tutorials that utilize Kerberos as the underlying technology for authentication and secure communication.
Introduction
The
LoginModuledocumentation describes the interface that must be implemented by authentication technology providers.LoginModules are plugged in under applications to provide a particular type of authentication.While applications write to the
LoginContextApplication Programming Interface (API), authentication technology providers implement theLoginModuleinterface. AConfigurationspecifies theLoginModule(s) to be used with a particular login application. DifferentLoginModules can be plugged in under the application without requiring any modifications to the application itself.The
LoginContextis responsible for reading theConfigurationand instantiating the specifiedLoginModules. EachLoginModuleis initialized with aSubject, aCallbackHandler, sharedLoginModulestate, andLoginModule-specific options.The
Subjectrepresents the user or service currently being authenticated and is updated by aLoginModulewith relevantPrincipals and credentials if authentication succeeds.LoginModules use theCallbackHandlerto communicate with users (to prompt for user names and passwords, for example), as described in the login method description. Note that theCallbackHandlermay be null. ALoginModulethat requires aCallbackHandlerto authenticate theSubjectmay throw aLoginExceptionif it was initialized with anullCallbackHandler.LoginModules optionally use the shared state to share information or data among themselves.The
LoginModule-specific options represent the options configured for thisLoginModulein the loginConfiguration. The options are defined by theLoginModuleitself and control the behavior within it. For example, aLoginModulemay define options to support debugging/testing capabilities. Options are defined using a key-value syntax, such as debug=true. TheLoginModulestores the options as aMapso that the values may be retrieved using the key. Note that there is no limit to the number of options aLoginModulechooses to define.The calling application sees the authentication process as a single operation invoked via a call to the
LoginContext'sloginmethod. However, the authentication process within eachLoginModuleproceeds in two distinct phases. In the first phase of authentication, theLoginContext'sloginmethod invokes theloginmethod of eachLoginModulespecified in theConfiguration. Theloginmethod for aLoginModuleperforms the actual authentication (prompting for and verifying a password for example) and saves its authentication status as private state information. Once finished, theLoginModule'sloginmethod returnstrue(if it succeeded) orfalse(if it should be ignored), or it throws aLoginExceptionto specify a failure. In the failure case, theLoginModulemust not retry the authentication or introduce delays. The responsibility of such tasks belongs to the application. If the application attempts to retry the authentication, eachLoginModule'sloginmethod will be called again.In the second phase, if the
LoginContext's overall authentication succeeded (calls to the relevant required, requisite, sufficient and optionalLoginModules'loginmethods succeeded), then thecommitmethod for eachLoginModulegets invoked. (For an explanation of theLoginModuleflags required, requisite, sufficient and optional, please consult thejavax.security.auth.login.Configurationdocumentation and Appendix B: Login Configuration Files in the JAAS Reference Guide.) Thecommitmethod for aLoginModulechecks its privately saved state to see if its own authentication succeeded. If the overallLoginContextauthentication succeeded and theLoginModule's own authentication succeeded, then thecommitmethod associates the relevantPrincipals (authenticated identities) and credentials (authentication data such as cryptographic keys) with theSubject.If the
LoginContext's overall authentication failed (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONALLoginModules'loginmethods did not succeed), then theabortmethod for eachLoginModulegets invoked. In this case, theLoginModuleremoves/destroys any authentication state originally saved.Logging out a
Subjectinvolves only one phase. TheLoginContextinvokes theLoginModule'slogoutmethod. Thelogoutmethod for theLoginModulethen performs the logout procedures, such as removingPrincipals or credentials from theSubject, or logging session information.
LoginModuleThe steps required in order to implement and test a
LoginModuleare the following:
- Step 1: Understand the Authentication Technology
- Step 2: Name the
LoginModuleImplementation- Step 3: Implement the Abstract
LoginModuleMethods- Step 4: Choose or Write a Sample Application
- Step 5: Compile the
LoginModuleand Application- Step 6: Prepare for Testing
- Step 6a: Place Your
LoginModuleand Application Code in JAR Files- Step 6b: Decide Where to Store the JAR Files
- Step 6c: Set
LoginModuleand Application JAR File Permissions- Step 6d: Create a Configuration Referencing the LoginModule
- Step 7: Test Use of the
LoginModule- Step 8: Document Your
LoginModuleImplementation- Step 9: Make
LoginModuleJAR File and Documents AvailableThe steps required to implement and test a new
LoginModulefollow. Please reference the SampleLoginModule and other files described in the JAAS Reference Guide for examples of what may be done for the various steps.
Step 1: Understand the Authentication Technology
The first thing you need to do is understand the authentication technology to be implemented by your newLoginModuleprovider, and determine its requirements.One thing you will need to determine is whether or not your
LoginModulewill require some form of user interaction (retrieving a user name and password, for example). If so, you will need to become familiar with theCallbackHandlerinterface and thejavax.security.auth.callbackpackage. In that package you will find several possibleCallbackimplementations to use. (Alternatively, you can create your ownCallbackimplementations.) TheLoginModulewill invoke theCallbackHandlerspecified by the application itself and passed to theLoginModule'sinitializemethod. TheLoginModulepasses theCallbackHandleran array of appropriateCallbacks. See the login method in Step 3.Note that it is possible for
LoginModuleimplementations not to have any end-user interactions. SuchLoginModules would not need to access thecallbackpackage.Another thing you should determine is what configuration options you want to make available to the user, who specifies configuration information in whatever form the current Configuration implementation expects (for example, in files). For each option, decide the option name and possible values. For example, if a
LoginModulemay be configured to consult a particular authentication server host, decide on the option's key name ("auth_server", for example), as well as the possible server hostnames valid for that option ("server_one.foo.com" and "server_two.foo.com", for example).Step 2: Name the
LoginModuleImplementationDecide on the proper package and class name for yourLoginModule.For example, a
LoginModuledeveloped by IBM might be calledcom.ibm.auth.Modulewherecom.ibm.authis the package name andModuleis the name of theLoginModuleclass implementation.Step 3: Implement the Abstract
LoginModuleMethodsThe
See below and theLoginModuleinterface specifies five abstract methods that require implementations:LoginModuleAPI for more information on each method above.In addition to these methods, a
LoginModuleimplementation must provide a public constructor with no arguments. This allows for its proper instantiation by aLoginContext. Note that if no such constructor is provided in yourLoginModuleimplementation, a default no-argument constructor is automatically inherited from theObjectclass.void initialize(Subject subject,
CallbackHandlerCallbackHandler, Map sharedState, Map options);The
initializemethod is called to initialize theLoginModulewith the relevant authentication and state information.This method is called by a
LoginContextimmediately after thisLoginModulehas been instantiated, and prior to any calls to its other public methods. The method implementation should store away the provided arguments for future use.The
initializemethod may additionally peruse the provided sharedState to determine what additional authentication state it was provided by otherLoginModules, and may also traverse through the provided options to determine what configuration options were specified to affect theLoginModule's behavior. It may save option values in variables for future use.Note: JAAS LoginModules may use the options defined in PAM (
use_first_pass,try_first_pass,use_mapped_pass, andtry_mapped_pass) to achieve single-signon. See Making Login Services Independent from Authentication Technologies for further information.Below is a list of options commonly supported by LoginModules. Note that the following is simply a guideline. Modules are free to support a subset (or none) of the following options.
try_first_pass- Iftrue, the first LoginModule in the stack saves the password entered, and subsequent LoginModules also try to use it. If authentication fails, the LoginModules prompt for a new password and retry the authentication.
use_first_pass- Iftrue, the first LoginModule in the stack saves the password entered, and subsequent LoginModules also try to use it. LoginModules do not prompt for a new password if authentication fails (authentication simply fails).
try_mapped_pass- Iftrue, the first LoginModule in the stack saves the password entered, and subsequent LoginModules attempt to map it into their service-specific password. If authentication fails, the LoginModules prompt for a new password and retry the authentication.
use_mapped_pass- Iftrue, the first LoginModule in the stack saves the password entered, and subsequent LoginModules attempt to map it into their service-specific password. LoginModules do not prompt for a new password if authentication fails (authentication simply fails).
moduleBanner- Iftrue, then when invoking the CallbackHandler, the LoginModule provides a TextOutputCallback as the first Callback, which describes the LoginModule performing the authentication.
debug- Iftrue, instructs a LoginModule to output debugging information.The
initializemethod may freely ignore state or options it does not understand, although it would be wise to log such an event if it does occur.Note that the
LoginContextinvoking thisLoginModule(and the other configuredLoginModules, as well), all share the same references to the providedSubjectandsharedState. Modifications to theSubjectandsharedStatewill, therefore, be seen by all.boolean login() throws LoginException;
The
loginmethod is called to authenticate aSubject. This is phase 1 of authentication.This method implementation should perform the actual authentication. For example, it may cause prompting for a user name and password, and then attempt to verify the password against a password database. Another example implementation may inform the user to insert their finger into a fingerprint reader, and then match the input fingerprint against a fingerprint database.
If your
LoginModulerequires some form of user interaction (retrieving a user name and password, for example), it should not do so directly. That is because there are various ways of communicating with a user, and it is desirable forLoginModules to remain independent of the different types of user interaction. Rather, theLoginModule'sloginmethod should invoke thehandlemethod of the theCallbackHandlerpassed to theinitializemethod to perform the user interaction and set appropriate results, such as the user name and password. TheLoginModulepasses theCallbackHandleran array of appropriateCallbacks, for example a NameCallback for the user name and a PasswordCallback for the password, and theCallbackHandlerperforms the requested user interaction and sets appropriate values in theCallbacks. For example, to process aNameCallback, theCallbackHandlermay prompt for a name, retrieve the value from the user, and call theNameCallback'ssetNamemethod to store the name.The authentication process may also involve communication over a network. For example, if this method implementation performs the equivalent of a kinit in Kerberos, then it would need to contact the KDC. If a password database entry itself resides in a remote naming service, then that naming service needs to be contacted, perhaps via the Java Naming and Directory Interface (JNDI). Implementations might also interact with an underlying operating system. For example, if a user has already logged into an operating system like Solaris or Windows NT, this method might simply import the underlying operating system's identity information.
The
loginmethod should
- Determine whether or not this
LoginModuleshould be ignored. One example of when it should be ignored is when a user attempts to authenticate under an identity irrelevant to thisLoginModule(if a user attempts to authenticate as root using NIS, for example). If thisLoginModuleshould be ignored,loginshould returnfalse. Otherwise, it should do the following:
- Call the
CallbackHandlerhandlemethod if user interaction is required.
- Perform the authentication.
- Store the authentication result (success or failure).
- If authentication succeeded, save any relevant state information that may be needed by the
commitmethod.
- Return
trueif authentication succeeds, or throw aLoginExceptionsuch asFailedLoginExceptionif authentication fails.Note that the
loginmethod implementation should not associate any newPrincipalor credential information with the savedSubjectobject. This method merely performs the authentication, and then stores away the authentication result and corresponding authentication state. This result and state will later be accessed by thecommitorabortmethod. Note that the result and state should typically not be saved in the sharedStateMap, as they are not intended to be shared with otherLoginModules.An example of where this method might find it useful to store state information in the sharedState
Mapis whenLoginModules are configured to share passwords. In this case, the entered password would be saved as shared state. By sharing passwords, the user only enters the password once, and can still be authenticated to multipleLoginModules. The standard conventions for saving and retrieving names and passwords from the sharedStateMapare the following:
javax.security.auth.login.name- Use this as the shared state map key for saving/retrieving a name.
javax.security.auth.login.password- Use this as the shared state map key for saving/retrieving a password.If authentication fails, the
loginmethod should not retry the authentication. This is the responsibility of the application. MultipleLoginContextloginmethod calls by an application are preferred over multiple login attempts from withinLoginModule.login().boolean commit() throws LoginException;
The
commitmethod is called to commit the authentication process. This is phase 2 of authentication when phase 1 succeeds. It is called if theLoginContext's overall authentication succeeded (that is, if the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONALLoginModules succeeded.)This method should access the authentication result and corresponding authentication state saved by the
loginmethod.If the authentication result denotes that the
loginmethod failed, then thiscommitmethod should remove/destroy any corresponding state that was originally saved.If the saved result instead denotes that this
LoginModule'sloginmethod succeeded, then the corresponding state information should be accessed to build any relevantPrincipaland credential information. SuchPrincipals and credentials should then be added to theSubjectstored away by theinitializemethod.After adding
Principals and credentials, dispensable state fields should be destroyed expeditiously. Likely fields to destroy would be user names and passwords stored during the authentication process.The
commitmethod should save private state indicating whether the commit succeeded or failed.The following chart depicts what a
LoginModule'scommitmethod should return. The different boxes represent the different situations that may occur. For example, the top-left corner box depicts what thecommitmethod should return if both the previous call tologinsucceeded and thecommitmethod itself succeeded.\ LOGIN \ COMMIT \ \ SUCCESS FAILURE +--------------+-----------------+ | | | SUCCESS | return TRUE | throw EXCEPTION | | | | +--------------+-----------------+ | | | FAILURE | return FALSE | return FALSE | | | | +--------------+-----------------+
boolean abort() throws LoginException;
The
abortmethod is called to abort the authentication process. This is phase 2 of authentication when phase 1 fails. It is called if theLoginContext's overall authentication failed.This method first accesses this
LoginModule's authentication result and corresponding authentication state saved by thelogin(and possiblycommit) methods, and then clears out and destroys the information. Sample state to destroy would be user names and passwords.If this
LoginModule's authentication attempt failed, then there shouldn't be any private state to clean up.The following charts depict what a
LoginModule'sabortmethod should return. This first chart assumes that the previous call tologinsucceeded. For instance, the top-left corner box depicts what theabortmethod should return if both the previous call tologinandcommitsucceeded, and theabortmethod itself also succeeded.\ COMMIT \ ABORT (assumes LOGIN method succeeded) \ \ SUCCESS FAILURE +--------------+-----------------+ | | | SUCCESS | return TRUE | throw EXCEPTION | | | | +--------------+-----------------+ | | | FAILURE | return TRUE | throw EXCEPTION | | | | +--------------+-----------------+The second chart depicts what a
LoginModule'sabortmethod should return, assuming that the previous call tologinfailed. For instance, the top-left corner box depicts what theabortmethod should return if the previous call tologinfailed, the previous call tocommitsucceeded, and theabortmethod itself also succeeded.\ COMMIT \ ABORT (assumes LOGIN method failed) \ \ SUCCESS FAILURE +--------------+-----------------+ | | | SUCCESS | return FALSE | return FALSE | | | | +--------------+-----------------+ | | | FAILURE | return FALSE | return FALSE | | | | +--------------+-----------------+boolean logout() throws LoginException;
The
logoutmethod is called to log out aSubject.This method removes
Principals, and removes/destroys credentials associated with theSubjectduring thecommitoperation. This method should not touch thosePrincipals or credentials previously existing in theSubject, or those added by otherLoginModules.If the
Subjecthas been marked read-only (theSubject'sisReadOnlymethod returns true), then this method should only destroy credentials associated with theSubjectduring thecommitoperation (removing the credentials is not possible). If theSubjecthas been marked as read-only and the credentials associated with theSubjectduring thecommitoperation are not destroyable (they do not implement theDestroyableinterface), then this method may throw aLoginException.The
logoutmethod should returntrueif logout succeeds, or otherwise throw a LoginException.Step 4: Choose or Write a Sample Application
Either choose an existing sample application for your testing, or write a new one. See JAAS Reference Guide for information about application requirements and a sample application you can use for your testing.
Step 5: Compile the
LoginModuleand ApplicationCompile your newLoginModuleand the application you will use for testing.Step 6: Prepare for Testing
Step 6a: Place Your
LoginModuleand Application Code in JAR FilesPlace your
LoginModuleand application code in separate JAR files, in preparation for referencing the JAR files in the policy in Step 6c. Here is a sample command for creating a JAR file:jar cvf <JAR file name> <list of classes, separated by spaces>This command creates a JAR file with the specified name containing the specified classes.
For more information on the jar tool, see jar (for Solaris) (for Microsoft Windows).
Step 6b: Decide Where to Store the JAR Files
The application can be stored essentially anywhere you like.
Your
LoginModulecan also be placed anywhere you (and other clients) like. If theLoginModuleis fully trusted, it can be placed in the JRE'slib/ext(standard extension) directory.You will need to test the
LoginModulebeing located both in thelib/extdirectory and elsewhere because in one situation yourLoginModulewill need to explicitly be granted permissions required for any security-sensitive operations it does, while in the other case such permissions are not needed.If your
LoginModuleis placed in the JRE'slib/extdirectory, it will be treated as an installed extension and no permissions need to be granted, since the default system policy file grants all permissions to installed extensions.If your
LoginModuleis placed anywhere else, the permissions need to be granted, for example bygrantstatements in a policy file.Decide where you will store the
LoginModuleJAR file for testing the case where it is not an installed extension. In the next step, you grant permissions to the JAR file, in the specified location.Step 6c: Set
LoginModuleand Application JAR File PermissionsIf your
LoginModuleand/or application performs security-sensitive tasks that will trigger security checks (making network connections, reading or writing files on a local disk, etc), it will need to be granted the required permissions if it is not an installed extension (see Step 6b) and it is run while a security manager is installed.Since
LoginModules usually associatePrincipals and credentials with an authenticated Subject, some types of permissions aLoginModulewill typically require are AuthPermissions with target names "modifyPrincipals", "modifyPublicCredentials", and "modifyPrivateCredentials".A sample statement granting permissions to a
LoginModulewhose code is inMyLM.jarappears below. Such a statement could appear in a policy file. In this example, theMyLM.jarfile is assumed to be in the/localWorkdirectory.grant codeBase "file:/localWork/MyLM.jar" { permission javax.security.auth.AuthPermission "modifyPrincipals"; permission javax.security.auth.AuthPermission "modifyPublicCredentials"; permission javax.security.auth.AuthPermission "modifyPrivateCredentials"; };Note: Since a
LoginModuleis always invoked within anAccessController.doPrivilegedcall, it should not have to calldoPrivilegeditself. If it does, it may inadvertently open up a security hole. For example, aLoginModulethat invokes the application-providedCallbackHandlerinside adoPrivilegedcall opens up a security hole by permitting the application'sCallbackHandlerto gain access to resources it would otherwise not have been able to access.Step 6d: Create a Configuration Referencing the LoginModule
Because JAAS supports a pluggable authentication architecture, your new
LoginModulecan be used without requiring modifications to existing applications. Only the loginConfigurationneeds to be updated in order to indicate use of a newLoginModule.The default
Configurationimplementation from Sun Microsystems reads configuration information from configuration files, as described in com.sun.security.auth.login.ConfigFile.html.Create a configuration file to be used for testing. For example, to configure the previously-mentioned hypothetical IBM
LoginModulefor an application, the configuration file might look like this:AppName { com.ibm.auth.Module REQUIRED debug=true; };whereAppNameshould be whatever name the application uses to refer to this entry in the login configuration file. The application specifies this name as the first argument to theLoginContextconstructor.
Step 7: Test Use of the
LoginModuleFinally, test your application and its use of the
LoginModule. When you run the application, specify the login configuration file to be used. For example, suppose your application is namedMyApp, it is located inMyApp.jar, and your configuration file istest.conf. You could run the application and specify the configuration file via the following:java -classpath MyApp.jar -Djava.security.auth.login.config=test.conf MyAppType all that on one line. Multiple lines are used here for legibility.
To specify a policy file named
my.policyand run the application with a security manager installed, do the following:java -classpath MyApp.jar -Djava.security.manager -Djava.security.policy=my.policy -Djava.security.auth.login.config=test.conf MyAppAgain, type all that on one line.
You may want to configure the
LoginModulewith a debug option to help ensure that it is working correctly.Debug your code and continue testing as needed. If you have problems, review the steps above and ensure they are all completed.
Be sure to vary user input and the
LoginModuleoptions specified in the configuration file.Be sure to also include testing using different installation options (e.g., making the
LoginModulean installed extension or placing it on the class path) and execution environments (with or without a security manager running). Installation options are discussed in Step 6b. In particular, in order to ensure yourLoginModuleworks when a security manager is installed and theLoginModuleand application are not installed extensions, you need to test such an installation and execution environment, after granting required permissions, as described in Step 6c.If you find during testing that your
LoginModuleor application needs modifications, make the modifications, recompile (Step 5), place the updated code in a JAR file (Step 6a), re-install the JAR file (Step 6b), if needed fix or add to the permissions (Step 6c), if needed modify the login configuration file (Step 6d), and then re-run the application and repeat these steps as needed.Step 8: Document Your
LoginModuleImplementationThe next step is to write documentation for clients of your
LoginModule. Example documentation you may want to include is:
- A README or User Guide describing
- the authentication process employed by your
LoginModuleimplementation.
- information on how to install the
LoginModule.
- configuration options accepted by the
LoginModule. For each option, specify the option name and possible values (or types of values), as well as the behavior the option controls.
- the permissions required by your
LoginModulewhen it is run with a security manager (and it is not an installed extension).
- An example
Configurationfile that references your newLoginModule.
- An example policy file granting your
LoginModulethe required permissions.
- API documentation. Putting javadoc comments into your source code as you write it will make the API javadocs easy to generate.
Step 9: Make
LoginModuleJAR File and Documents AvailableThe final step is to make your
LoginModuleJAR file and documentation available to clients.
Last update: August 8, 2001