I am using an openLDAP server to authenticate my users on my quarkus app.
Everything works well but I would like to retrieve my user data.
I thought it would be in the method identity.getAttributes() but this gives me an empty Map.
Here is an example of a user :
# tesla, example.com
dn: uid=tesla,dc=example,dc=com
objectClass: inetOrgPerson
objectClass: organizationalPerson
objectClass: person
objectClass: top
objectClass: posixAccount
cn: Nikola Tesla
sn: Tesla
uid: tesla
mail: tesla#ldap.forumsys.com
uidNumber: 88888
gidNumber: 99999
homeDirectory: home
Here is also my ldap configuration :
quarkus.security.ldap.enabled=true
quarkus.security.ldap.dir-context.url=ldap://ldap.forumsys.com:389/
quarkus.security.ldap.dir-context.principal=cn=read-only-admin,dc=example,dc=com
quarkus.security.ldap.dir-context.password=password
quarkus.security.ldap.identity-mapping.rdn-identifier=uid
quarkus.security.ldap.identity-mapping.search-base-dn=dc=example,dc=com
quarkus.security.ldap.identity-mapping.attribute-mappings."0".from=cn
quarkus.security.ldap.identity-mapping.attribute-mappings."0".to=groups
quarkus.security.ldap.identity-mapping.attribute-mappings."0".filter=(member=uid={0})
quarkus.security.ldap.identity-mapping.attribute-mappings."0".filter-base-dn=dc=example,dc=com
How can I get my user mail and CN ?
Thank by advance you for your help,
Thomas
Ok, I found an answer, which is quite ugly but that does work.
Because I couldn't find how to get my data with the framework, I tried to get it in command line by using ldapsearch.
Thus, I can retrieve my user data by running the command :
ldapsearch -H ldap://ldap.forumsys.com:389/ -x -D "cn=read-only-admin,dc=example,dc=com" -w password -b "dc=example,dc=com" -LLL "(uid=tesla)"
which gives me :
dn: uid=tesla,dc=example,dc=com
objectClass: inetOrgPerson
objectClass: organizationalPerson
objectClass: person
objectClass: top
objectClass: posixAccount
cn: Nikola Tesla
sn: Tesla
uid: tesla
mail: tesla#ldap.forumsys.com
uidNumber: 88888
gidNumber: 99999
homeDirectory: home
Now, the authentication works, from my SecurityIdentity I can retrieve the login (with : identity.getPrincipal().getName()) and I have this command that gives me the data for a particular user. I think you got the point.
I run this command inside my java and retrieve my data manually.
Here is the code in Java :
final String cmd = "ldapsearch -H " + ldapUrl + " -x -D \"" + ldapUser + "\" -w " + ldapPassword + " -b \"" + ldapFilter + "\" -LLL \"(uid=" + login + ")\"";
String[] shellCommand = { "/bin/bash", "-c", cmd };
final Map<String, String> map = new HashMap<>();
Process process = Runtime.getRuntime().exec(shellCommand);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
if(line.contains(": ")) {
final String key = line.split(": ")[0];
final String value = line.split(": ")[1];
map.put(key, value);
}
}
return map;
Please notice that I get only one value per key because the data I am interested in have one line.
Here is the answer I found for my problem.
I hope someone will find something cleaner.
Thomas
Related
I'm doing my first steps on LDAP with spring boot. I have managed to authenticate my user which is listed in my ldif file:
dn: dc=parascus,dc=de
objectclass: top
objectclass: domain
objectclass: extensibleObject
dc: parascus
dn: ou=groups,dc=parascus,dc=de
objectclass: top
objectclass: organizationalUnit
ou: groups
dn: ou=people,dc=parascus,dc=de
objectclass: top
objectclass: organizationalUnit
ou: people
dn: uid=jsmith,ou=people,dc=parascus,dc=de
objectclass: top
objectclass: person
objectclass: inetOrgPerson
cn: Smith, John
sn: Smith
uid: jsmith
userPassword: scrambled
dn: cn=developers,ou=groups,dc=parascus,dc=de
objectclass: top
objectclass: groupOfUniqueNames
cn: developers
ou: developer
uniqueMember: uid=jsmith,ou=people,dc=parascus,dc=de
Now I'm in my controller method and try to get the cn property "Smith, John":
#GetMapping("/profile")
public String index(Authentication authentication) {
return "Profile of " + authentication.getName();
}
But I only get the uid "jsmith". Can somebody give me a hint how I can get all the information or at last the cn entry?
Kind Regards
Parascus
You will need to supply a UserDetailsContextMapper to tell Spring Security how to extract details from the DirContext.
You do this when exposing the LdapAuthenticationProvider:
#Bean
LdapAuthenticationProvider ldap(LdapAuthenticator authenticator) {
LdapAuthenticationProvider ldap = new LdapAuthenticationProvider(authenticator);
ldap.setUserDetailsContextMapper(new PersonContextMapper());
return ldap;
}
Spring Security ships with a couple of built-in context mappers, one for the person schema (PersonContextMapper) and another for the inetOrgPerson schema (InetOrgPersonContextMapper).
With the above configuration, you can do either:
public String index(Authentication authentication) {
Person person = (Person) authentication.getPrincipal();
String[] cn = person.getCn();
return "Profile of " + cn[cn.length - 1];
}
or
public String index(#AuthenticationPrincipal Person person) {
String[] cn = person.getCn();
return "Profile of " + cn[cn.length - 1];
}
If your entries use neither the person nor the inetOrgPerson schema, you can create your own UserDetailsContextMapper.
I need some help. I'm able to log in to the system with my LDAP users but all of them have the Admin role although I've configured the LDAP group mappings.
I think that this could be related with the actual schema I've in my LDAP. I'm far from being an LDAP expert, so I would like to receive some help from you.
This is a common user account of LDAP:
#rmartinez, people, domain.com
dn: uid=rmartinez,ou=people,dc=domain,dc=domain
cn: Ricardo Martinez
gidNumber: 100
givenName: Ricardo
homeDirectory: /home/rmartinez
loginShell: /bin/bash
objectClass: top
objectClass: posixAccount
objectClass: inetOrgPerson
sn: Martinez
uid: rmartinez
uidNumber: 10009
userPassword:: e3NzaGF9dWN0RGJ1Njg4ejZPeittYUxrdlRoZWUrM2VWUFdFcFpVQT09
This is one of the groups mapped to Grafana:
# Directores, group, domain.com
dn: cn=Directores,ou=group,dc=domain,dc=com
cn: Directores
gidNumber: 10002
member: uid=sbenito,ou=people,dc=domain,dc=com
member: uid=jsaez,ou=people,dc=domain,dc=com
member: uid=rsanchez,ou=people,dc=domain,dc=com
objectClass: top
objectClass: posixGroup
objectClass: groupOfNames
userPassword:: e3NzaGF9cmhxUVdhWmdZNy83NHM3cGxPYVd6VFFDQVlOWlRsUk5TZz09
And this is how my ldap.toml looks like:
# To troubleshoot and get more log info enable ldap debug logging in grafana.ini
#[log]
#filters = ldap:debug
verbose_logging = true
[[servers]]
# Ldap server host (specify multiple hosts space separated)
host = "dc01.domain.com"
# Default port is 389 or 636 if use_ssl = true
port = 389
# Set to true if ldap server supports TLS
use_ssl = true
# Set to true if connect ldap server with STARTTLS pattern (create connection in insecure, then upgrade to secure connection with TLS)
start_tls = true
# set to true if you want to skip ssl cert validation
ssl_skip_verify = true
# set to the path to your root CA certificate or leave unset to use system defaults
root_ca_cert = "/etc/ldap/certs/caskmf.pem"
# Authentication against LDAP servers requiring client certificates
client_cert = "/etc/ldap/certs/dc01srvcert.pem"
client_key = "/etc/ldap/certs/dc01key.pem"
# Search user bind dn
bind_dn = "cn=Manager,dc=domain,dc=com"
# Search user bind password
# If the password contains # or ; you have to wrap it with triple quotes. Ex """#password;"""
bind_password = 'admin'
# User search filter, for example "(cn=%s)" or "(sAMAccountName=%s)" or "(uid=%s)"
search_filter = "(uid=%s)"
# An array of base dns to search through
search_base_dns = ["dc=domain,dc=com"]
## For Posix or LDAP setups that does not support member_of attribute you can define the below settings
## Please check grafana LDAP docs for examples
group_search_filter = "(&(objectClass=posixGroup))"
group_search_base_dns = ["ou=group,dc=domain,dc=com"]
group_search_filter_user_attribute = "uid"
# Specify names of the ldap attributes your ldap uses
[servers.attributes]
name = "givenName"
surname = "sn"
username = "cn"
member_of = "memberOf"
#email = "email"
# Map ldap groups to grafana org roles
[[servers.group_mappings]]
group_dn = "cn=Administradores,ou=group,dc=domain,dc=com"
org_role = "Admin"
# To make user an instance admin (Grafana Admin) uncomment line below
grafana_admin = true
# The Grafana organization database id, optional, if left out the default org (id 1) will be used
# org_id = 1
[[servers.group_mappings]]
group_dn = "cn=Operadores,ou=group,dc=domain,dc=com"
org_role = "Editor"
[[servers.group_mappings]]
# If you want to match all (or no ldap groups) then you can use wildcard
group_dn = "cn=Directores,ou=group,dc=domain,dc=com"
org_role = "Viewer"
Please, could you help me? I've tried almost everything. I think that this is related because users do not have any attribute that makes reference to the group they belong to.
This is the log:
Dec 18 09:25:55 persephone grafana-server[4668]: t=2019-12-18T09:25:55+0100 lvl=info msg="LDAP enabled, reading config file" logger=ldap file=/etc/grafana/ldap.toml
Dec 18 09:25:55 persephone grafana-server[4668]: t=2019-12-18T09:25:55+0100 lvl=info msg="Searching for user's groups" logger=ldap filter="(&(objectClass=posixGroup))"
Dec 18 09:25:55 persephone grafana-server[4668]: t=2019-12-18T09:25:55+0100 lvl=dbug msg="LDAP users found" logger=ldap users="([]*models.ExternalUserInfo) (len=1 cap=1) {\n (*models.ExternalUserInfo)(0xc0000da510)({\n OAuthToken: (*oauth2.Token)(<nil>),\n AuthModule: (string) (len=4) \"ldap\",\n AuthId: (string) (len=38) \"uid=pgambarte,ou=people,dc=domain,dc=com\",\n UserId: (int64) 0,\n Email: (string) \"\",\n Login: (string) (len=14) \"Pilar Gambarte\",\n Name: (string) (len=14) \"Pilar Gambarte\",\n Groups: ([]string) (len=3 cap=4) {\n (string) (len=37) \"cn=Operadores,ou=group,dc=domain,dc=com\",\n (string) (len=42) \"cn=Administradores,ou=group,dc=domain,dc=com\",\n (string) (len=37) \"cn=Directores,ou=group,dc=domain,dc=com\"\n },\n OrgRoles: (map[int64]models.RoleType) (len=1) {\n (int64) 1: (models.RoleType) (len=5) \"Admin\"\n },\n IsGrafanaAdmin: (*bool)(0xc00082fa20)(true),\n IsDisabled: (bool) false\n })\n}\n"
Dec 18 09:25:55 persephone grafana-server[4668]: t=2019-12-18T09:25:55+0100 lvl=dbug msg="user auth token created" logger=auth tokenId=14 userId=2 clientIP=10.0.2.2 userAgent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36" authToken=f8152859f8f2421705b2b967a742bcfbfb7ec4d5e0ef0cebe9575dbb399a54c9
Dec 18 09:25:55 persephone grafana-server[4668]: t=2019-12-18T09:25:55+0100 lvl=info msg="Successful Login" logger=http.server User="Pilar Gambarte"
Dec 18 09:25:55 persephone grafana-server[4668]: t=2019-12-18T09:25:55+0100 lvl=dbug msg="seen token" logger=auth tokenId=14 userId=2 clientIP=10.0.2.2 userAgent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36" authToken=f8152859f8f2421705b2b967a742bcfbfb7ec4d5e0ef0cebe9575dbb399a54c9
Dec 18 09:25:55 persephone grafana-server[4668]: t=2019-12-18T09:25:55+0100 lvl=dbug msg="Updating last user_seen_at" logger=context userId=2 orgId=1 uname="Pilar Gambarte" user_id=2
Thank you so much.
Regards.
#tomgalpin This is the log of a user who belongs to Directores group instead of Administradores:
Dec 18 14:15:48 persephone grafana-server[1730]: t=2019-12-18T14:15:48+0100 lvl=info msg="LDAP enabled, reading config file" logger=ldap file=/etc/grafana/ldap.toml
Dec 18 14:15:48 persephone grafana-server[1730]: t=2019-12-18T14:15:48+0100 lvl=info msg="Searching for user's groups" logger=ldap filter="(&(objectClass=posixGroup))"
Dec 18 14:15:48 persephone grafana-server[1730]: t=2019-12-18T14:15:48+0100 lvl=dbug msg="LDAP users found" logger=ldap users="([]*models.ExternalUserInfo) (len=1 cap=1) {\n (*models.ExternalUserInfo)(0xc00047d680)({\n OAuthToken: (*oauth2.Token)(<nil>),\n AuthModule: (string) (len=4) \"ldap\",\n AuthId: (string) (len=36) \"uid=sbenito,ou=people,dc=domain,dc=com\",\n UserId: (int64) 0,\n Email: (string) \"\",\n Login: (string) (len=11) \"Sara Benito\",\n Name: (string) (len=11) \"Sara Benito\",\n Groups: ([]string) (len=3 cap=4) {\n (string) (len=37) \"cn=Operadores,ou=group,dc=domain,dc=com\",\n (string) (len=42) \"cn=Administradores,ou=group,dc=domain,dc=com\",\n (string) (len=37) \"cn=Directores,ou=group,dc=domain,dc=com\"\n },\n OrgRoles: (map[int64]models.RoleType) (len=1) {\n (int64) 1: (models.RoleType) (len=5) \"Admin\"\n },\n IsGrafanaAdmin: (*bool)(0xc0005c5fc0)(true),\n IsDisabled: (bool) false\n })\n}\n"
Dec 18 14:15:48 persephone grafana-server[1730]: t=2019-12-18T14:15:48+0100 lvl=info msg="Successful Login" logger=http.server User="Sara Benito"
And here is the Administradores group ldapsearch output. As you can see pgambarte belongs to it. the issue is that Grafana is not filtering correctly the membership of the users to the different groups and all the users, no matter what group belongs to, have the same role: admin.
Pgambarte is in Administradores Group:
# Administradores, group, domain.com
dn: cn=Administradores,ou=group,dc=domain,dc=com
cn: Administradores
gidNumber: 10001
member: uid=pgambarte,ou=people,dc=domain,dc=com
member: uid=rmartin,ou=people,dc=domain,dc=com
member: uid=rmartinez,ou=people,dc=domain,dc=com
member: uid=pgomez,ou=people,dc=domain,dc=com
member: uid=jramirez,ou=people,dc=domain,dc=com
objectClass: posixGroup
objectClass: groupOfNames
objectClass: top
Thank you for your assistance.
I use
debian 9
gitlab-ce 11.10.4-ce.0
omnibus install via apt
openldap 2.4.44
ldap configuration
Configured /etc/ldap/ldap.conf :
BASE dc=serverX,dc=lan
URI ldap://serverX.lan
TLS_CACERT /etc/ssl/certs/ca-certificates.crt
Configured /etc/gitlab/gitlab.rb :
gitlab_rails['ldap_enabled'] = true
gitlab_rails['ldap_servers'] = YAML.load <<-EOS
label: 'Gitlab LDAP'
host: '10.0.0.1'
port: 389
uid: 'sAMAccountName'
method: 'plain' # "tls" or "ssl" or "plain"
bind_dn: 'cn=admin,ou=users,dc=serverX,dc=lan'
password: 'xxxx'
encryption: 'plain'
active_directory: false
allow_username_or_email_login: true
block_auto_created_users: false
base: 'ou=users,dc=serverX,dc=lan'
EOS
Output of gitlab-rake gitlab:ldap:check is OK :
# gitlab-rake gitlab:ldap:check
Checking LDAP ...
LDAP: ... Server: ldapmain
LDAP authentication... Success
LDAP users with access to your GitLab server (only showing the first 100 results)
Checking LDAP ... Finished
Users created from phpldapadmin :
Searched tons of web ressources, but I can't figure out the way to create LDAP users or use existing ones.
I don't know what is the issue and why I get Invalid credentials for user.name : I edited via phpladmin the Password attribute (md5) and I type the same one in the LDAP Gitlab login page :
Gitlab logs :
==> /var/log/gitlab/gitlab-rails/production.log <==
Started POST "/users/auth/ldapmain/callback" for 10.0.0.1 at 2019-05-16 07:56:16 +0200
Processing by OmniauthCallbacksController#failure as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"[FILTERED]", "username"=>"user.name", "password"=>"[FILTERED]"}
Redirected to http://domainX.lan/users/sign_in
Completed 302 Found in 411ms (ActiveRecord: 23.1ms)
Started GET "/users/sign_in" for 10.0.0.1 at 2019-05-16 07:56:17 +0200
Processing by SessionsController#new as HTML
Completed 200 OK in 119ms (Views: 104.6ms | ActiveRecord: 7.5ms)
==> /var/log/gitlab/unicorn/unicorn_stdout.log <==
I, [2019-05-16T07:56:16.907169 #3996] INFO -- omniauth: (ldapmain) Callback phase initiated.
E, [2019-05-16T07:56:16.917884 #3996] ERROR -- omniauth: (ldapmain) Authentication failure! invalid_credentials: OmniAuth::Strategies::LDAP::InvalidCredentialsError, Invalid credentials for user.name
The slapcat output with targeted user to login :
dn: uuid=gquenot,ou=users,dc=serverX,dc=lan
cn:: abcdef123456789==
sn: Foo Bar
objectClass: inetOrgPerson
objectClass: top
structuralObjectClass: inetOrgPerson
entryUUID: 5133fc-0be-2039-9825-cd7
creatorsName: cn=admin,dc=serverX,dc=lan
createTimestamp: 20190516045340Z
userPassword:: xxxxxxxx
mail: me#example.com
entryCSN: 20190516101837.136599Z#000000#000#000000
modifiersName: cn=admin,dc=serverX,dc=lan
modifyTimestamp: 20190516101837Z
Anyone knows what's wrong ?
Maybe someone can give me a sample ldiff and a working configuration ?
Edit:
slapadd try with this ldiff via slapadd -f file.ldiff :
dn: cn=admin,dc=serverX,dc=lan
objectClass: inetOrgPerson
objectClass: organizationalPerson
objectClass: person
objectClass: top
cn: Firstname Lastname
givenName: Gilles
sn: Quenot
uid: gquenot
mail: me#example.com
userPassword: {MD5}xxxxxxxxxxxxxx
Error :
5cdd8fe4 slapcat_so.txt: line 1: unknown directive <dn:> outside backend info and database definitions.
slapadd: bad configuration file!
Edit2
Fixed with :
ldapadd -x -H ldap://serverX:389 -D 'cn=admin,dc=serverX,dc=lan' -W -f stuff.ldiff
And updated password in phpldapadmin
Your Gitlab configuration targets Active Directory while you are using OpenLDAP to authenticate users, so the first thing to do is fixing the following parameters in /etc/gitlab/gitlab.rb:
uid: 'uid'
active_directory: false
I don't know what is the purpose of attributes in the context of an authentication (edit: attributes are used to synchronize user data from ldap to its Gitlab account, it shouldn't matter for the authentication itself).
Maybe there are other issues like the user's uid not being 'user.name', or the base being too narrow for example (user.name entry may not be under ou=people), if you don't know use the base dn as base search, or check by running a search with/without the 'ou' part :
ldapsearch -H ldap://10.0.0.1:389 -D cn=admin,dc=serverX,dc=lan -W -b ou=people,dc=serverX,dc=lan uid=user.name \*
I'd also check the credentials themselves directly against ldap , ie. not through Gitlab, by performing roughly the same query but using user.name bindings, here we actually tests that he can bind and read its own entry :
ldapsearch -H ldap://10.0.0.1:389 -D <user.name dn> -W -b <user.name dn> -s base \*
Also GitLab documentation insists on the fact that LDAP users must have an email address set, regardless of whether it is used to log in.
A typical ldif file containing user.name entry to be created using ldapadd -f (provided that the ou and dc's mentioned in its distinguished name exists) would look like this :
# user.name entry
dn: uid=user.name,ou=users,dc=serverX,dc=lan
objectClass: inetOrgPerson
objectClass: organizationalPerson
objectClass: person
objectClass: top
cn: Firstname Lastname
givenName: Firstname
sn: Lastname
uid: user.name
mail: user.name#domain.com
userPassword: {MD5}<base64EncodedHash>
I don't know though if/how GitLab is aware of the password encryption scheme (seems there is no config for this or I missed it).
You can create a test case entry :
replace the <base64EncodedHash> with {MD5}CY9rzUYh03PK3k6DJie09g== (it represents the password test, if you need I have a script to generate them).
don't forget also to replace the dc's with the real ones in the dn
beware of empty lines and \t in the ldif file as it can break your ldap add/modify operations.
run ldapadd -x -H ldap://10.0.0.1:389 -D cn=admin,dc=serverX,dc=lan -W -f ldifFilename to create the user entry.
running the 1st ldapsearch cmd above, you should see a result for that new entry.
running the second one, binding with the user credentials 'test' and searching for its own entry (hence the -b base parameter pointing to himself to avoid permission issues during search), you should again see the same result.
In gitlab.rb :
gitlab_rails['ldap_servers'] = YAML.load <<-EOS
label: 'Gitlab LDAP'
host: '10.0.0.1'
port: 389
uid: 'uid'
bind_dn: 'cn=admin,ou=users,dc=serverX,dc=lan'
password: 'xxxx'
encryption: 'plain'
active_directory: false
allow_username_or_email_login: false
block_auto_created_users: false
base: 'ou=users,dc=serverX,dc=lan'
If you can bind with this user but not through gitlab ui, that could mean it does not handle the {MD5} authentication scheme.
I was facing the same problem - Invalid credentials even though I was keying in the correct credentials.
This solution worked for me -
My gitlab.rb had to be changed in this manner below. Previously I had not changed the value of 'uid' which was set to 'sAMAccountName', as you can see I commented it
and changed the value to 'uid' itself. So 'uid' => 'uid' is the setting. Prior to doing this setting even when I was running the command -
gitlab-rake gitlab:ldap:check , The output used to show - LDAP authentication... Success
but no list of ldap users were shown.
As soon as I changed the uid value as above, the rake command worked smoothly and showed me the list of all ldap users in the dc. Post this I was able to login also into the application through the UI
Note - Replace all the XXX with your own values.
gitlab_rails['ldap_enabled'] = true
gitlab_rails['prevent_ldap_sign_in'] = false
gitlab_rails['ldap_servers'] = {
'main' => {
'label' => 'LDAP',
'host' => '10.XXX.XX.XX',
'port' => 389,
# 'uid' => 'sAMAccountName',
'uid' => 'uid',#mandatory need to keep the value as 'uid' only
'encryption' => 'plain',
'verify_certificates' => false,
'bind_dn' => 'cn=XXX,dc=XXXX,dc=XXX',
'password' => 'XXX',
'verify_certificates' => false,
# 'tls_options' => {
# 'ca_file' => '',
# 'ssl_version' => '',
# 'ciphers' => '',
# 'cert' => '',
# 'key' => ''
# },
'timeout' => 10,
'active_directory' => false,
'allow_username_or_email_login' => false,
'block_auto_created_users' => false,
'base' => 'dc=XXX,dc=XX',
# 'user_filter' => '',
# 'attributes' => {
# 'username' => ['uid', 'userid', 'sAMAccountName'],
# 'email' => ['mail', 'email', 'userPrincipalName'],
# 'name' => 'cn',
# 'first_name' => 'givenName',
# 'last_name' => 'sn'
# },
'lowercase_usernames' => true,
# EE Only
# 'group_base' => '',
# 'admin_group' => '',
# 'external_groups' => [],
# 'sync_ssh_keys' => false
}
}
I install GitLab using Docker Engine
https://docs.gitlab.com/ee/install/docker.html
LDAP Configuration
https://docs.gitlab.com/ee/administration/auth/ldap/#integrate-ldap-with-gitlab
sudo docker exec -it gitlab nano /etc/gitlab/gitlab.rb
## LDAP Settings
##! Docs: https://docs.gitlab.com/omnibus/settings/ldap.html
##! **Be careful not to break the indentation in the ldap_servers block. It is
##! in yaml format and the spaces must be retained. Using tabs will not work.**
gitlab_rails['ldap_enabled'] = true
gitlab_rails['prevent_ldap_sign_in'] = false
##! **remember to close this block with 'EOS' below**
gitlab_rails['ldap_servers'] = YAML.load <<-'EOS'
main: # 'main' is the GitLab 'provider ID' of this LDAP server
label: 'LDAP'
host: 'ipa.example.com'
port: 636
uid: 'uid'
bind_dn: 'uid=gitlab,cn=users,cn=accounts,dc=example,dc=com'
password: 'gitlabpassword'
encryption: 'simple_tls' # "start_tls" or "simple_tls" or "plain"
verify_certificates: false
smartcard_auth: false
active_directory: false
allow_username_or_email_login: false
lowercase_usernames: false
block_auto_created_users: false
base: 'cn=users,cn=accounts,dc=example,dc=com'
user_filter: ''
EOS
Save configuration, and than reconfigure GitLab:
sudo docker exec -it gitlab /bin/bash
root#gitlab:/# gitlab-ctl reconfigure
root#gitlab:/# gitlab-ctl restart
Check if LDAP integration works:
root#gitlab:/# gitlab-rake gitlab:ldap:check
Checking LDAP ...
LDAP: ... Server: ldapmain
not verifying SSL hostname of LDAPS server 'ipa.example.com:636'
LDAP authentication... Success
LDAP users with access to your GitLab server (only showing the first 100 results)
DN: uid=admin,cn=users,cn=accounts,dc=example,dc=com uid: admin
DN: uid=gitlab,cn=users,cn=accounts,dc=example,dc=com uid: gitlab
Checking LDAP ... Finished
Attempting to fire-up an AD-like server for verifying ldap queries for 'user' entities.
The test:
import org.zapodot.junit.ldap.EmbeddedLdapRule
import org.zapodot.junit.ldap.EmbeddedLdapRuleBuilder
class FooSpec extends Specification {
#Rule
public EmbeddedLdapRule embeddedLdapRule = EmbeddedLdapRuleBuilder
.newInstance()
.withSchema('schema.ldif')
.importingLdifs('import.ldif')
//...
}
schema.ldif:
dn: cn=user,cn=schema,cn=configuration,dc=example,dc=com
changetype: add
objectclass: classSchema
governsId: 1.2.840.113556.1.5.9
objectClassCategory: 1
subClassOf: organizationalPerson
lDAPDisplayName: user
description: a user
import.ldif:
dn: CN=alice,DC=example,dc=com
objectClass: inetOrgPerson
objectClass: organizationalPerson
objectClass: person
objectClass: user
cn: alice
sn: alice
Getting:
Unable to add entry 'CN=alice,DC=example,dc=com' because it violates the provided schema: The entry contains object class user which is not defined in the schema.
What am I doing wrong?
Thanks!
This does not seem to be a Spock-specific question, I guess you are having an LDAP syntax problem here. I have no idea about LDAP, I just got curious and used this LDIF file provided by the tool used by you (embedded-ldap-junit) in order to show you how it works beautifully with Spock if you just use correct LDAP definitions in your resource file:
package de.scrum_master.stackoverflow
import com.unboundid.ldap.sdk.SearchScope
import org.junit.Rule
import org.zapodot.junit.ldap.EmbeddedLdapRule
import org.zapodot.junit.ldap.EmbeddedLdapRuleBuilder
import spock.lang.Specification
import spock.lang.Unroll
class EmbeddedLDAPServerTest extends Specification {
static final String BASE_DN = "dc=zapodot,dc=org"
#Rule
public EmbeddedLdapRule embeddedLdapRule = EmbeddedLdapRuleBuilder
.newInstance()
.usingDomainDsn(BASE_DN)
.importingLdifs('example.ldif')
.build()
#Unroll
def "Search for #searchFor"() {
given:
def connection = embeddedLdapRule.ldapConnection()
when:
def searchResult = connection.search(BASE_DN, SearchScope.SUB, "($searchFor)")
then:
searchResult.entryCount == entryCount
where:
searchFor | entryCount
"objectClass=person" | 1
"cn=Sondre Eikanger Kvalo" | 1
"ou=people" | 1
"ou=groups" | 1
"objectclass=organizationalUnit" | 2
"objectclass=top" | 4
}
}
I am using apacheds (running on port 10389) for LDAP services. My gerrit instance is able to to a handshake with LDAP, however, user authentication is never successful. I always get this error message:
username: name.surname
password: password
INFO com.google.gerrit.httpd.auth.ldap.LdapLoginServlet : 'name.surname' failed to sign in: No such user: name.surname
My gerrit.conf is as follows:
[gerrit]
basePath = /home/gerrit2/git
canonicalWebUrl = http://gerrit.myorg.com:8080/
[database]
type = mysql
hostname = localhost
database = reviewdb
username = gerrit2
[index]
type = LUCENE
[auth]
type = LDAP
[ldap]
server = ldap://localhost:10389
username = cn=abc def,ou=user,dc=myorg,dc=com
accountBase = ou=user,dc=myorg,dc=com
groupBase = ou=user,dc=myorg,dc=com
referral = follow
accountFullName = cn
accountEmailAddress = mail
[sendemail]
smtpServer = localhost
[container]
user = gerrit2
javaHome = /usr/lib/jvm/java-1.7.0-openjdk-1.7.0.71.x86_64/jre
[sshd]
listenAddress = *:29418
[httpd]
listenUrl = http://*:8080/
[cache]
directory = cache
The ldif file through which I added the user into partition ou=user,dc=myorg,dc=com is:
dn: cn=name.surname,ou=user,dc=myorg,dc=com
objectclass: inetOrgPerson
objectclass: organizationalPerson
objectclass: person
objectclass: top
cn: name.surname
description: Gerrit Administrator
sn: name.surname
mail: name.surname#myorg.com
userpassword: password
Can anyone explain where's the problem happening? I assume by default the gerrit username is matched against the CN (by appending against the baseDN). Please correct me if I am wrong.
Oh, I got the answer. By default username is matched against uid. To match username against CN, the following line has to be added to [ladp] subsection in gerrit.config file:
(cn=${username})