APIdia Launch Partner
Top Description Fields Constructors Methods
com.sun.security.auth.module

public Class LdapLoginModule

extends Object
implements LoginModule
Class Inheritance
All Implemented Interfaces
javax.security.auth.spi.LoginModule
Imports
java.security.Principal, java.util.Arrays, .Hashtable, .Map, .Set, java.util.regex.Matcher, .Pattern, javax.naming.*, javax.naming.directory.*, javax.naming.ldap.*, javax.security.auth.*, javax.security.auth.callback.*, javax.security.auth.login.*, javax.security.auth.spi.*, com.sun.security.auth.LdapPrincipal, .UserPrincipal

This LoginModule performs LDAP-based authentication. A username and password is verified against the corresponding user credentials stored in an LDAP directory. This module requires the supplied CallbackHandler to support a NameCallback and a PasswordCallback. If authentication is successful then a new LdapPrincipal is created using the user's distinguished name and a new UserPrincipal is created using the user's username and both are associated with the current Subject.

This module operates in one of three modes: search-first, authentication-first or authentication-only. A mode is selected by specifying a particular set of options.

In search-first mode, the LDAP directory is searched to determine the user's distinguished name and then authentication is attempted. An (anonymous) search is performed using the supplied username in conjunction with a specified search filter. If successful then authentication is attempted using the user's distinguished name and the supplied password. To enable this mode, set the userFilter option and omit the authIdentity option. Use search-first mode when the user's distinguished name is not known in advance.

In authentication-first mode, authentication is attempted using the supplied username and password and then the LDAP directory is searched. If authentication is successful then a search is performed using the supplied username in conjunction with a specified search filter. To enable this mode, set the authIdentity and the userFilter options. Use authentication-first mode when accessing an LDAP directory that has been configured to disallow anonymous searches.

In authentication-only mode, authentication is attempted using the supplied username and password. The LDAP directory is not searched because the user's distinguished name is already known. To enable this mode, set the authIdentity option to a valid distinguished name and omit the userFilter option. Use authentication-only mode when the user's distinguished name is known in advance.

The following option is mandatory and must be specified in this module's login Configuration:

userProvider=ldap_urls
This option identifies the LDAP directory that stores user entries. ldap_urls is a list of space-separated LDAP URLs (RFC 2255) that identifies the LDAP server to use and the position in its directory tree where user entries are located. When several LDAP URLs are specified then each is attempted, in turn, until the first successful connection is established. Spaces in the distinguished name component of the URL must be escaped using the standard mechanism of percent character ('%') followed by two hexadecimal digits (see java.net.URI). Query components must also be omitted from the URL.

Automatic discovery of the LDAP server via DNS (RFC 2782) is supported (once DNS has been configured to support such a service). It is enabled by omitting the hostname and port number components from the LDAP URL.

This module also recognizes the following optional Configuration options:

userFilter=ldap_filter
This option specifies the search filter to use to locate a user's entry in the LDAP directory. It is used to determine a user's distinguished name. ldap_filter is an LDAP filter string (RFC 2254). If it contains the special token "{USERNAME}" then that token will be replaced with the supplied username value before the filter is used to search the directory.
authIdentity=auth_id
This option specifies the identity to use when authenticating a user to the LDAP directory. auth_id may be an LDAP distinguished name string (RFC 2253) or some other string name. It must contain the special token "{USERNAME}" which will be replaced with the supplied username value before the name is used for authentication. Note that if this option does not contain a distinguished name then the userFilter option must also be specified.
authzIdentity=authz_id
This option specifies an authorization identity for the user. authz_id is any string name. If it comprises a single special token with curly braces then that token is treated as a attribute name and will be replaced with a single value of that attribute from the user's LDAP entry. If the attribute cannot be found then the option is ignored. When this option is supplied and the user has been successfully authenticated then an additional UserPrincipal is created using the authorization identity and it is associated with the current Subject.
useSSL
if false, this module does not establish an SSL connection to the LDAP server before attempting authentication. SSL is used to protect the privacy of the user's password because it is transmitted in the clear over LDAP. By default, this module uses SSL.
useFirstPass
if true, this module retrieves the username and password from the module's shared state, using "javax.security.auth.login.name" and "javax.security.auth.login.password" as the respective keys. The retrieved values are used for authentication. If authentication fails, no attempt for a retry is made, and the failure is reported back to the calling application.
tryFirstPass
if true, this module retrieves the username and password from the module's shared state, using "javax.security.auth.login.name" and "javax.security.auth.login.password" as the respective keys. The retrieved values are used for authentication. If authentication fails, the module uses the CallbackHandler to retrieve a new username and password, and another attempt to authenticate is made. If the authentication fails, the failure is reported back to the calling application.
storePass
if true, this module stores the username and password obtained from the CallbackHandler in the module's shared state, using "javax.security.auth.login.name" and "javax.security.auth.login.password" as the respective keys. This is not performed if existing values already exist for the username and password in the shared state, or if authentication fails.
clearPass
if true, this module clears the username and password stored in the module's shared state after both phases of authentication (login and commit) have completed.
debug
if true, debug messages are displayed on the standard output stream.

Arbitrary "JNDI properties" may also be specified in the Configuration. They are added to the environment and passed to the LDAP provider. Note that the following four JNDI properties are set by this module directly and are ignored if also present in the configuration:

Three sample Configurations are shown below. The first one activates search-first mode. It identifies the LDAP server and specifies that users' entries be located by their uid and objectClass attributes. It also specifies that an identity based on the user's employeeNumber attribute should be created. The second one activates authentication-first mode. It requests that the LDAP server be located dynamically, that authentication be performed using the supplied username directly but without the protection of SSL and that users' entries be located by one of three naming attributes and their objectClass attribute. The third one activates authentication-only mode. It identifies alternative LDAP servers, it specifies the distinguished name to use for authentication and a fixed identity to use for authorization. No directory search is performed.

ExampleApplication {
        com.sun.security.auth.module.LdapLoginModule REQUIRED
             userProvider="ldap://ldap-svr/ou=people,dc=example,dc=com"
             userFilter="(&(uid={USERNAME})(objectClass=inetOrgPerson))"
             authzIdentity="{EMPLOYEENUMBER}"
             debug=true;
    };

    ExampleApplication {
        com.sun.security.auth.module.LdapLoginModule REQUIRED
            userProvider="ldap:///cn=users,dc=example,dc=com"
            authIdentity="{USERNAME}"
            userFilter="(&(|(samAccountName={USERNAME})(userPrincipalName={USERNAME})(cn={USERNAME}))(objectClass=user))"
            useSSL=false
            debug=true;
    };

    ExampleApplication {
        com.sun.security.auth.module.LdapLoginModule REQUIRED
            userProvider="ldap://ldap-svr1 ldap://ldap-svr2"
            authIdentity="cn={USERNAME},ou=people,dc=example,dc=com"
            authzIdentity="staff"
            debug=true;
    };

Since
1.6

Field Summary

Modifier and TypeField and Description
private static final String
private String
private boolean
private boolean
private static final String
private String
private String
private UserPrincipal
private CallbackHandler
private boolean
private boolean
private SearchControls
private LdapContext
private boolean
private Matcher
private Matcher
private Hashtable<String, Object>
private LdapPrincipal
private Map<String, ?>
private char[]
private static final String
private Map<String, Object>
private boolean
private Subject
private boolean
private boolean
private boolean
private static final String
private static final String
private String
private String
private static final String
private static final Pattern
private static final String
private UserPrincipal
private String
private boolean

Constructor Summary

AccessConstructor and Description
public
LdapLoginModule()

Creates an LdapLoginModule.

Method Summary

Modifier and TypeMethod and Description
public boolean

Returns:

false if this LoginModule's own login and/or commit attempts failed, and true otherwise.
abort
()

Implements javax.security.auth.spi.LoginModule.abort.

Abort user authentication.

private void
attemptAuthentication(boolean
boolean that tells this method whether to retrieve the password from the sharedState.
getPasswdFromSharedState
)

Attempt authentication

private void
cleanState()

Clean out state because of a failed authentication attempt

public boolean

Returns:

true if this LoginModule's own login and commit attempts succeeded, or false otherwise.
commit
()

Implements javax.security.auth.spi.LoginModule.commit.

Complete user authentication.

private String

Returns:

the modified username with its characters escaped as needed
escapeUsernameChars
()

Modify the supplied username to encode characters that must be escaped according to RFC 4515: LDAP: String Representation of Search Filters.

private String

Returns:

the user's distinguished name or an empty string if none was found.
findUserDN
(LdapContext
an LDAP context to use for the search
ctx
)

Search for the user's entry.

private void
getUsernamePassword(boolean
boolean that tells this method whether to retrieve the password from the sharedState.
getPasswdFromSharedState
)

Get the username and password.

public void
initialize(Subject
the Subject to be authenticated.
subject
,
CallbackHandler
a CallbackHandler to acquire the username and password.
callbackHandler
,
Map<String, ?>
shared LoginModule state.
sharedState
,
Map<String, ?>
options specified in the login Configuration for this particular LoginModule.
options
)

Implements javax.security.auth.spi.LoginModule.initialize.

Initialize this LoginModule.

public boolean

Returns:

true always, since this LoginModule should not be ignored.
login
()

Implements javax.security.auth.spi.LoginModule.login.

Begin user authentication.

public boolean

Returns:

true in all cases since this LoginModule should not be ignored.
logout
()

Implements javax.security.auth.spi.LoginModule.logout.

Logout a user.

private String

Returns:

the modified string
replaceUsernameToken
(Matcher
the replacement pattern
matcher
,
String
the target string
string
,
String
the supplied username
username
)

Replace the username token

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

AUTHC_IDENTITYback to summary
private static final String AUTHC_IDENTITY
authcIdentityback to summary
private String authcIdentity
authFirstback to summary
private boolean authFirst
authOnlyback to summary
private boolean authOnly
AUTHZ_IDENTITYback to summary
private static final String AUTHZ_IDENTITY
authzIdentityback to summary
private String authzIdentity
authzIdentityAttrback to summary
private String authzIdentityAttr
authzPrincipalback to summary
private UserPrincipal authzPrincipal
callbackHandlerback to summary
private CallbackHandler callbackHandler
clearPassback to summary
private boolean clearPass
commitSucceededback to summary
private boolean commitSucceeded
constraintsback to summary
private SearchControls constraints
ctxback to summary
private LdapContext ctx
debugback to summary
private boolean debug
filterMatcherback to summary
private Matcher filterMatcher
identityMatcherback to summary
private Matcher identityMatcher
ldapEnvironmentback to summary
private Hashtable<String, Object> ldapEnvironment
ldapPrincipalback to summary
private LdapPrincipal ldapPrincipal
optionsback to summary
private Map<String, ?> options
passwordback to summary
private char[] password
PASSWORD_KEYback to summary
private static final String PASSWORD_KEY
sharedStateback to summary
private Map<String, Object> sharedState
storePassback to summary
private boolean storePass
subjectback to summary
private Subject subject
succeededback to summary
private boolean succeeded
tryFirstPassback to summary
private boolean tryFirstPass
useFirstPassback to summary
private boolean useFirstPass
USER_FILTERback to summary
private static final String USER_FILTER
USER_PROVIDERback to summary
private static final String USER_PROVIDER
userFilterback to summary
private String userFilter
usernameback to summary
private String username
USERNAME_KEYback to summary
private static final String USERNAME_KEY
USERNAME_PATTERNback to summary
private static final Pattern USERNAME_PATTERN
USERNAME_TOKENback to summary
private static final String USERNAME_TOKEN
userPrincipalback to summary
private UserPrincipal userPrincipal
userProviderback to summary
private String userProvider
useSSLback to summary
private boolean useSSL

Constructor Detail

LdapLoginModuleback to summary
public LdapLoginModule()

Creates an LdapLoginModule.

Method Detail

abortback to summary
public boolean abort() throws LoginException

Implements javax.security.auth.spi.LoginModule.abort.

Abort user authentication.

This method is called if the overall authentication failed. (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules did not succeed).

If this LoginModule's own authentication attempt succeeded (checked by retrieving the private state saved by the login and commit methods), then this method cleans up any state that was originally saved.

Returns:boolean

false if this LoginModule's own login and/or commit attempts failed, and true otherwise.

Exceptions
LoginException:
if the abort fails.
attemptAuthenticationback to summary
private void attemptAuthentication(boolean getPasswdFromSharedState) throws LoginException

Attempt authentication

Parameters
getPasswdFromSharedState:boolean

boolean that tells this method whether to retrieve the password from the sharedState.

Exceptions
LoginException:
if the authentication attempt fails.
cleanStateback to summary
private void cleanState()

Clean out state because of a failed authentication attempt

commitback to summary
public boolean commit() throws LoginException

Implements javax.security.auth.spi.LoginModule.commit.

Complete user authentication.

This method is called if the LoginContext's overall authentication succeeded (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules succeeded).

If this LoginModule's own authentication attempt succeeded (checked by retrieving the private state saved by the login method), then this method associates an LdapPrincipal and one or more UserPrincipals with the Subject located in the LoginModule. If this LoginModule's own authentication attempted failed, then this method removes any state that was originally saved.

Returns:boolean

true if this LoginModule's own login and commit attempts succeeded, or false otherwise.

Exceptions
LoginException:
if the commit fails
escapeUsernameCharsback to summary
private String escapeUsernameChars()

Modify the supplied username to encode characters that must be escaped according to RFC 4515: LDAP: String Representation of Search Filters. The following characters are encoded as a backslash "\" (ASCII 0x5c) followed by the two hexadecimal digits representing the value of the escaped character: '*' (ASCII 0x2a) '(' (ASCII 0x28) ')' (ASCII 0x29) '\' (ASCII 0x5c) '\0'(ASCII 0x00)

Returns:String

the modified username with its characters escaped as needed

findUserDNback to summary
private String findUserDN(LdapContext ctx) throws LoginException

Search for the user's entry. Determine the distinguished name of the user's entry and optionally an authorization identity for the user.

Parameters
ctx:LdapContext

an LDAP context to use for the search

Returns:String

the user's distinguished name or an empty string if none was found.

Exceptions
LoginException:
if the user's entry cannot be found.
getUsernamePasswordback to summary
private void getUsernamePassword(boolean getPasswdFromSharedState) throws LoginException

Get the username and password. This method does not return any value. Instead, it sets global name and password variables.

Also note that this method will set the username and password values in the shared state in case subsequent LoginModules want to use them via use/tryFirstPass.

Parameters
getPasswdFromSharedState:boolean

boolean that tells this method whether to retrieve the password from the sharedState.

Exceptions
LoginException:
if the username/password cannot be acquired.
initializeback to summary
public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState, Map<String, ?> options)

Implements javax.security.auth.spi.LoginModule.initialize.

Initialize this LoginModule.

Parameters
subject:Subject

the Subject to be authenticated.

callbackHandler:CallbackHandler

a CallbackHandler to acquire the username and password.

sharedState:Map<String, ?>

shared LoginModule state.

options:Map<String, ?>

options specified in the login Configuration for this particular LoginModule.

Annotations
@SuppressWarnings:unchecked
loginback to summary
public boolean login() throws LoginException

Implements javax.security.auth.spi.LoginModule.login.

Begin user authentication.

Acquire the user's credentials and verify them against the specified LDAP directory.

Returns:boolean

true always, since this LoginModule should not be ignored.

Exceptions
LoginException:
if this LoginModule is unable to perform the authentication.
FailedLoginException:
if the authentication fails.
logoutback to summary
public boolean logout() throws LoginException

Implements javax.security.auth.spi.LoginModule.logout.

Logout a user.

This method removes the Principals that were added by the commit method.

Returns:boolean

true in all cases since this LoginModule should not be ignored.

Exceptions
LoginException:
if the logout fails.
replaceUsernameTokenback to summary
private String replaceUsernameToken(Matcher matcher, String string, String username)

Replace the username token

Parameters
matcher:Matcher

the replacement pattern

string:String

the target string

username:String

the supplied username

Returns:String

the modified string