LDAP error on bind method when trying to connect to LDAP - ldap

At my end(locally), I am using Sun ONE LDAP server, and where my application is deployed, they use MS AD. I store the values of User Name and Password (LDAP user name and password) in one table. In Sun ONE, I precede my user name with "cn=" and at my end I am able to connect to LDAP server, but where the application is deployed, the get bind error :-
Bind: Error: netscape.ldap.LDAPException: error result (49); 80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 525, vece
I have my piece of code as follows for connection :-
try {
conn.connect(ldapHost,ldapPort);
}
catch(LDAPException ldapexception)
{
ldapexception.printStackTrace(System.out);
}
try {
conn.bind(ldapVersion,loginDN,loginDN_Password);
}
catch(LDAPException ldapexception)
{
ldapexception.printStackTrace(System.out);
}
I am getting this error at bind.
I googled about this error, and I found that login credentials is the problem.
But I have verified at their end, the login credentials are correct, the only difference at my end and their end is that I precede my user name with "cn=" and they do not.
I tried doing the same, but still getting the same error.
Can anyone help me on this ?

The purpose of the BIND request is to exchange authentication information between client and server. If the BIND was successful, a SUCCESS result code is returned to the client in the BIND response, along with any controls. The name or bind DN must be an LDAP DN as defined in RFC4511 and RFC4514, therefore it must have the naming attribute (cn in your case).

Related

Automatically choose Auth0 DB Connection according to user's email address

I already read the multi-tenancy guide published, and I believe the solution I require for my app would be to create a separate DB Connection for each organization that I sign up.
My issue is that, since I'm going to be setting the connection parameter to a different name per client, I would have liked Universal Login to automatically determine the DB Connection name according to the user's email address. So, instead of the user manually providing some kind of a hint to which DB Connection I should authenticate them against, I would like to automatically determine that somehow.
Is there any way to do this?
I am assuming that you are using hosted login page. The easiest way to determine the connection based on client would be to pass the connection parameter when redirecting to /authorize endpoint. Thus, Lock will use the connection parameter passed in the URL as the connection to validate the user. For example:
https://[tenant]/authorize?
client_id=K8B5DJdStcZtUzbhaxAOzCrXNbo2kmXG&
response_type=token%20id_token&
redirect_uri=http://application_url&
scope=openid%20profile%20email%20&
connection=connection_name&state=123&nonce=345
Both auth0.js and auth0-spa-js can be used to pass the extra parameter(connection).
Second approach would be to use connectionResolver options if you are using Hosted Login Page+ Lock .
connectionResolver {Function}: When in use, provides an extensibility point to make it possible to choose which connection to use based on the username information. Has username, context, and callback as parameters. The callback expects an object like: {type: 'database', name: 'connection name'}.
var options = {
connectionResolver: function (username, context, cb) {
var domain = username.includes('#') && username.split('#')[1];
if (domain) {
// If the username is test#auth0.com, the connection used will be the `auth0.com` connection.
// Make sure you have a database connection with the name `auth0.com`.
cb({ type: 'database', name: domain });
} else {
// Use the default approach to figure it out the connection
cb(null);
}
}
}
Instead of username, you can take advantage of context object to identify the client (context.clientID) and choose the connection.

How to connect LDAP With username and password?

I have my Ldap working the only issue i'm facing was when I try to login with email that is when I land in the else part in the below code. If my username is different from email then it throws error. i.e if my email is 'skumar#gmail.com' and my username is 'saurakumar' then it will through invalid username password error.
As internally I'm using username to make email i.e if the user login with name 'karan' then i'm expecting the email to be karan #gmail.com which is not true in many scenario and the Authentication fails. I'm looking for some solution wherein I can login either via email or via username I'll be able to authenticate user. Below is the snippet of my code. Please suggest?
ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
ldapEnv.put(Context.PROVIDER_URL, url);
ldapEnv.remove(Context.SECURITY_PROTOCOL);
if (email == null) {
lContext = new InitialLdapContext(ldapEnv, null);
entryResult = searchUserEntry(lContext, user, searchCtrls);
final String usrDN = ((Context) entryResult.getObject()).getNameInNamespace();
lContext.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
lContext.addToEnvironment(Context.SECURITY_PRINCIPAL, usrDN);
lContext.addToEnvironment(Context.SECURITY_CREDENTIALS, pass);
lContext.reconnect(null);
} else {
ldapEnv.put(Context.SECURITY_PRINCIPAL, email);
ldapEnv.put(Context.SECURITY_CREDENTIALS, credentials);
lContext = new InitialLdapContext(ldapEnv, null);
return lContext;
searchUserEntry(lContext, user, searchCtrls);
}
Normally this is a 3-step process:
Bind to LDAP as an administrative user. Note that this should not be the master user defined in the configuration file: that's for OpenLDAP's use itself. Instead it should be a user mentioned in the DIT that has the appropriate search access for the next step.
Search for the user via some unique attribute, e.g. in your case email.
Using the found DN of the user and the password he specified, attempt to bind as that user (with the reconnect() method, after changing the environment of the context appropriately).
If all that succeeds, you have a login success. If (2) or (3) fail, you have a failure, and note that you should not tell the user which it was: otherwise you are leaking information to attackers. You should not mention whether it was the username (email) or the password that was wrong.

LDAP Authentication failed: Invalid Credentials

In Gforge, when a new user tries to log in; the user is automatically registered by fetching data from LDAP. It works fine for other users but one particular user is not able to log in and gets the error LDAP Authentication failed: Invalid Credentials . I don't understand what could be the issue? Could you please help?
This is the search function I am using.
ldap_bind($ldap, $dn, $pw)
$dn = ldap_get_dn($ldap, $entry);
$entry = ldap_first_entry($ldap,$res);
$res=ldap_search($ldap, $sys_ldap_base,$sys_ldap_id_attribute . '=' . $id,
array());
If it works for some users but not for one specific user, then it's something to do with the LDAP configuration, or with the characters in that user's ID or pwd.
Is the failing user in a different org/OU? Do they have accent characters in their username or password? These things can cause compatibility issues between GForge and the LDAP server.
Does this user have a much longer user name than other users? There is a GForge config setting called "usernameregex" that governs the complexity and length of allowed user names. Even though LDAP logins result in automatic account creation, the validation of the user's unix name might fail due to the regex in place. The error noted above could certainly be the catch-all message when this happens.
The default setting is "^[a-z0-9_.-]{3,15}$". You can change the upper length limit by changing the 15 to something else. The unix_name field in the GForge database is TEXT, so it can be extremely long (1GB?).
In GForge 6.3.x and earlier, you can find that setting in /etc/gforge/gforge.conf. Change the value and then update the system using:
cd /opt/gforge/bin && php create_config_cache.php
In GForge 6.4 and later, you can use the gf-config utility to set the value. It will take effect right away:
/opt/gforge/bin/gf-config set "usernameregex" "new regex value"

Which parameter is used for authentication in LDAP

In case of LDAP authenticaion, what are the parameters that are generally used for authentication. I guess using DN would be a headache for users logging in via ldap because it is too large to remember.
How is the option of using uid or sAMAccountName for authentication where in my implementation, I retrieve the dn of the corresponding uid or sAMAccountName and proceed to authentication.
Am I going the right track?
In LDAP, a connection or session can be authenticated. When an LDAP client makes a new connection to an LDAP directory server, the connection has an authorization state of anonymous. The LDAP client can request that the authorization state be changed by using the BIND request.
A BIND request has two forms: simple and SASL. Simple uses a distinguished name and a password, SASL uses one of a choice of mechanisms, for example, PLAIN, LOGIN, CRAM-MD5, DIGEST-MD5, GSSAPI, and EXTERNAL - all of which except for GSSAPI and EXTERNAL are too weak to use in production scenarios or mission-critical areas.
To Use the simple BIND, construct a BIND request and transmit it to the LDAP directory server. The LDAP directory server will respond with a BIND response in which is contained a result code. The result code is an integer, anything other zero indicates that the BIND request failed. If the result code is zero, the BIND request succeeded and the session authorization state has been changed to that of the distinguished name used in the BIND request.
Each subsequent BIND request on the same connection/session causes the authorization state to be set to anonymous and each successive successful BIND request on the same connection/session causes the authorization state to be set to the authorization state associated with the authentication ID, which is the distinguished name in the case of the simple BIND, but might be something else entirely where SASL is used - modern professional quality servers can map the incoming names to different DNs.
Whichever language is used, construct a BIND request, transmit it to the server, and interpret the response.
Update:
If the distinguished name is not known, or is too cumbersome (often the case with web application users who don't know how they are authenticated and would not care if they did know), the LDAP application should search the directory for the user. A successful search response always contains the distinguished name, which is then used in a simple BIND.
The search contains at a minimum, the following:
base object: a distinguished name superior to the user, for example, dc=example,dc=com
a scope: base level, one level below base, or subtree below base. For example, if users are located subordinate to ou=people,dc=example,dc=com, use base object ou=people,dc=example,dc=com and a scope of one-level. These search parameters find entries like: uid=user1,ou=people,dc=example,dc=com
a filter: narrows down the possible search results returned to the client, for example (objectClass=inetOrgPerson)
a list of requested attributes: the attributes from an entry to return to the client. In this case, use 1.1, which means no attributes and returns on the DN (distinguished name), which is all that is required for the simple BIND.
see also
the links in the about section here
LDAP servers only understand LDAP queries; they don't have "usernames" like you and I are used to.
For LDAP, to authenticate someone, you need to send a distinguished name of that person's (or entity's) entry in LDAP; along with their password.
Since you mentioned sAMAccountName I am assuming you are working with Active Directory. Active Directory allows anonymous binds - this means you can connect to it without providing any credentials; but cannot do any lookups without providing credentials.
If you are using python-ldap and Cython (and not IronPython which has access to the various .NET APIs that make this process very easy); then you follow these steps.
Typically you use a pre-set user that has appropriate rights to the tree, and connect to the directory with that user first, and then use that user's access for the rest of the authentication process; which generally goes like this:
Connect to AD with the pre-set user.
Query active directory with the pre-set user's credentials and search for the distinguished name based on the sAMAccountName that the user will enter as their "username" in your form.
Attempt to connect again to Active Directory using the distinguished name from step 2, and the password that the user entered in their form.
If this connection is successful, then the user is authenticated.
So you need two main things:
The login attribute (this is the "username" that LDAP understands)
A LDAP query that fetches information for your users
Following is some rough code that can do this for you:
AD_USER = 'your super user'
AD_PASSWORD = 'your super user password'
AD_BIND_ATTR = 'userPrincipalName' # this is the "login" for AD
AD_URL = "ldap://your-ad-server"
AD_DN = "DC=DOMAIN,DC=COM"
AD_LOGIN_ATTR = 'sAMAccountName' # this is what you user will enter in the form
# as their "login" name,
# this is what they use to login to Windows
# A listing of attributes you want to fetch for the user
AD_ATTR_SEARCH = ['cn',
'userPrincipalName',
'distinguishedName',
'mail',
'telephoneNumber','sAMAccountName']
def _getbinduser(user):
""" This method returns the bind user string for the user"""
user_dn = AD_DN
login_attr = '(%s=%s)' % (AD_LOGIN_ATTR,user)
attr_search = AD_ATTR_SEARCH
conn = ldap.initialize(AD_URL)
conn.set_option(ldap.OPT_REFERRALS,0)
conn.set_option(ldap.OPT_PROTOCOL_VERSION,3)
try:
conn.bind(AD_USER,AD_PASSWORD)
conn.result()
except:
exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
# Exit the script and print an error telling what happened.
sys.exit("LDAP Error (Bind Super User)\n ->%s" % exceptionValue)
try:
result = conn.search_s(user_dn,
ldap.SCOPE_SUBTREE,
login_attr, attr_search)
except:
exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
# Exit the script and print an error telling what happened.
sys.exit("LDAP Error (Search)\n ->%s" % exceptionValue)
# Return the user's entry from AD, which includes
# their 'distinguished name'
# we use this to authenticate the credentials the
# user has entered in the form
return result[0][1]
def authenticate(user,password):
bind_attr = AD_BIND_ATTR
user_dn = AD_DN
login_attr = '(%s=%s)' % (AD_LOGIN_ATTR,user)
data = _getbinduser(user)
if len(data) == 1:
return None
# Information we want to return from the directory
# for each user, season to taste.
info = {}
info['name'] = data['cn'][0]
info['email'] = data['mail'][0]
try:
info['phone'] = data['telephoneNumber'][0]
except KeyError:
info['phone'] = 'Not Available'
conn = ldap.initialize(Config.AD_URL)
conn.set_option(ldap.OPT_REFERRALS,0)
conn.set_option(ldap.OPT_PROTOCOL_VERSION,3)
try:
# Now we have the "bind attribute" (LDAP username) for our user
# we try and connect to see if LDAP will authenticate
conn.bind(data[bind_attr][0],password)
conn.search(user_dn,ldap.SCOPE_SUBTREE,login_attr,None)
conn.result()
return info
except (ldap.INVALID_CREDENTIALS,ldap.OPERATIONS_ERROR):
return None
One small expansion on Terry's excellent comment. If you store all your users in the same part of the DIT, and use the same attribute to identify them, you can programmatically construct the DN, rather than searching for it.

How do I access the user's password from LDAP in a LdapUserDetailsMapper using spring security?

We are using spring security in our web application based on spring MVC.
We are doing authentication using LDAP module of spring security which is working properly. Now I need to get the user password from LDAP for saving in the database.
For this I am using this in my code.
public class PersonContextMapper implements UserDetailsContextMapper {
public UserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<GrantedAuthority> authorities) {
Person.Essence p = new Person.Essence(ctx);
p.setUsername(username);
p.setAuthorities(authorities);
Object passwordValue = ctx.getObjectAttribute("userPassword");
return p.createUserDetails();
}
public void mapUserToContext(UserDetails user, DirContextAdapter ctx) {
Assert.isInstanceOf(Person.class, user, "UserDetails must be a Person instance");
Person p = (Person) user;
p.populateContext(ctx);
}
}
But I am not getting the any value for the password. Its always null.
Please help.
PS. My authentication is successful. It means password entered in the login form is matches properly with the password stored in the LDAP.
It might be that the authentication state of the connection does not have permission to read the value of the userPassword attribute. Most often, applications issue a BIND request to the directory server, including appropriate controls as necessary. The password is included in the BIND request and the directory server changes the authentication state of the connection upon successful completion of the BIND request. In any case, the value of the userPassword attribute is encrypted or hashed more often than not, and applications have no need to read the value.