James Jefferies and ShedCode Ltd

The world of James and ShedCode

Testing the Grails, Spring Security, LDAP Combo

| Comments

For running unit tests & integration tests, you might not want to run against an existing LDAP directory, maybe because you’re working remotely, or because you want a disposable directory to throw away after you’ve run your tests. Well, there is a grails plugin which adds an embedded LDAP directory (ApacheDS) to your application which can be fired up as/when required.

After installing the plugin, it requires a bit of configuration, so in your Config.groovy:

1
2
3
4
5
6
7
8
9
10
11
12
13
environments {
    development {       
      // Embedded ldap server 
      ldapServers {
          d1 {
              base = "dc=people,dc=companyname,dc=int"
              port = 10389
              indexed = ["objectClass", "uid", "mail", "userPassword"]
          }
      }
      grails.plugins.springsecurity.ldap.context.server = 'ldap://localhost:10389'
    }
    ....

So now, when the app is instantiated in the development environment, you have an ldap directory running on localhost, post 10389. You might want to change what is indexed depending on what details you actually want indexing!

If you wanted some default data loaded when the ldap server starts, simply add an ldif file to the grails-app/ldap-servers/d1/data directory. This gets auto loaded:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
dn: ou=group,dc=people,dc=companyname,dc=int
objectClass: top
objectClass: organizationalUnit
ou: group

dn: ou=People,dc=people,dc=companyname,dc=int
objectClass: organizationalUnit
ou: People

dn: uid=jjefferies,ou=People,dc=people,dc=companyname,dc=int
uid: jjefferies
objectClass: uidObject
objectClass: top
objectClass: person
objectClass: organizationalPerson
cn: James Jefferies
sn: Jefferies
userPassword: {SHA}ERnP637iUzV+A0oI2ETuol9v0g8=

To run unit tests against it, a reference to the server get’s injected in to your test class and then you can run some tests against it:

1
2
3
4
5
6
7
8
9
10
11
12
13
class LdapTests extends GroovyTestCase {

  def d1LdapServer
  
  void testLdapServerShouldExist() {
      assert d1LdapServer.exists("uid=jjefferies,ou=People,dc=people,dc=companyname,dc=int")
  }

  void testJJUserIsThere() {        
      def user = d1LdapServer["uid=jjefferies,ou=People,dc=people,dc=companyname,dc=int"]
      assert "James Jefferies" == user.cn.first() // cn is a multi valued string attribute       
  }
}

If you’re doing the full spring security with custom rolled retrieval of Roles and you want to test it, then you need to make sure you’ve bootstrapped those users too, so that the roles are retrieved as well as the user being authenticated.

Comments