blog.alfonsorv.com - Fotografía y desarrollo web

Fotografía y desarrollo web

Archivo de ‘grails’ Category

Grails LDAP authentication and authorization

12 comentarios

Today I’ve been investigating how to integrate a Grails aplication with an LDAP server to perform authentication and authorization.

There are several plugins available to do the authentication in a grails way.

My choice is Spring Security Core Plugin because it is mature and has several extension plugins to extend the functionality and provide integrations with external systems like Facebook, Twitter, OpenId and LDAP .

Installation and configuration are very well documented at : http://grails-plugins.github.com/grails-spring-security-core/docs/manual/

Peter Ledbrook wrote a great introductory article Simplified Spring Security with Grails .

I’ve updated the example application in the post to do the authentication using an LDAP Server.

My server has the following structure:

Sample LDAP structure

Yo can download the sample.ldif

Once you have all the LDAP structure, install the extension LDAP plugin for Spring Security Core

1
grails install-plugin spring-security-ldap

Now modify Config.groovy adding the specific configuration for LDAP spring-security-ldap

1
2
3
4
5
6
7
8
9
10
11
grails.plugins.springsecurity.providerNames = ['ldapAuthProvider','anonymousAuthenticationProvider','rememberMeAuthenticationProvider']
grails.plugins.springsecurity.ldap.context.managerDn = 'uid=admin,ou=system'
grails.plugins.springsecurity.ldap.context.managerPassword = 'YOUR_PASSWORD'
grails.plugins.springsecurity.ldap.context.server = 'ldap://10.99.8.135:10389'
grails.plugins.springsecurity.ldap.authorities.groupSearchBase = 'ou=Groups,dc=example,dc=com'
grails.plugins.springsecurity.ldap.authorities.retrieveGroupRoles = true
grails.plugins.springsecurity.ldap.authorities.retrieveDatabaseRoles = false
grails.plugins.springsecurity.ldap.authorities.groupSearchFilter = 'member={0}'
grails.plugins.springsecurity.ldap.search.base = 'dc=example,dc=com'
grails.plugins.springsecurity.ldap.search.attributesToReturn = ['mail', 'cn', 'sn', 'givenName', 'jpegPhoto' , 'telephoneNumber']
grails.plugins.springsecurity.ldap.authenticator.attributesToReturn = ['mail', 'cn', 'sn', 'givenName', 'jpegPhoto' , 'telephoneNumber']

 

Now you are ready to authenticate against your LDAP, also the group membership is readed from LDAP.

In the expample application the sec tag lib is used to show a link to the create post action based on the role of the logged user.

1
2
3
<sec:ifAllGranted roles="ROLE_USER">
  <g:link controller="post" action="timeline">My Timeline</g:link>
</sec:ifAllGranted>

How is this managed if you are using an LDAP? the answer is simple as everything in grails. Create a group in your LDAP named USER and add the users to it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
dn: cn=USER,ou=Groups,dc=example,dc=com
objectClass: groupOfNames
objectClass: top
cn: USER
description: USER_ROLE
member: uid=wpauli,ou=Users,dc=example,dc=com
member: uid=aeinstein,ou=Users,dc=example,dc=com
member: uid=mborn,ou=Users,dc=example,dc=com
member: uid=mcurie,ou=Users,dc=example,dc=com
member: uid=sito,ou=Users,dc=example,dc=com
createTimestamp: 20111121102018Z
creatorsName: 0.9.2342.19200300.100.1.1=admin,2.5.4.11=system
modifiersName: 0.9.2342.19200300.100.1.1=admin,2.5.4.11=system
modifyTimestamp: 20111121110901Z

I’ve added to the application some other properties that came from LDAP ( Photo, Telephone number, Full Name ).

This is done extending the org.springframework.security.core.userdetails.User to add all new attributes:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.userdetails.User
 
class MyUserDetails extends User {
 
    // extra instance variables final String fullname final String email final String title
    String fullname
    String email
    String title
    String phone
 
    byte[] photo
 
    MyUserDetails(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection authorities, String fullname, String email, String title, byte[] photo, String phone) {
 
        super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities)
 
        this.fullname = fullname
        this.email = email
        this.title = title
        this.photo = photo
        this.phone = phone
    }
 
}

And providing your own implementation for the org.springframework.security.ldap.userdetails.UserDetailsContextMapper interface.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import org.springframework.ldap.core.DirContextAdapter
import org.springframework.ldap.core.DirContextOperations
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.ldap.userdetails.UserDetailsContextMapper
/**
 *
 * @author SiTo
 */
 
class MyUserDetailsContextMapper implements UserDetailsContextMapper {
 
    UserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection authorities) {
 
        String fullname = ctx.originalAttrs.attrs['cn'].values[0]
        String email = ctx.originalAttrs.attrs['mail'].values[0].toString().toLowerCase()
 
        def title = ctx.originalAttrs.attrs['sn']
 
        def phone = ctx.getStringAttribute('telephoneNumber')
 
        byte[] photo = (byte[])ctx.getObjectAttribute('jpegPhoto')
 
        def userDetails = new MyUserDetails(username, '', true, true, true, true,
            authorities, fullname, email, title == null ? '' : title.values[0], photo, phone)
 
        return userDetails
    }
 
    void mapUserToContext(UserDetails user, DirContextAdapter ctx) {
        throw new IllegalStateException("Only retrieving data from LDAP is currently supported")
    }
 
}

The final step is register the custom implementation using the Spring DSL in the resources.groovy file

1
2
3
4
5
beans = {
   ldapUserDetailsMapper(MyUserDetailsContextMapper) {
      // bean attributes
   }
}

Now we are ready to use all new properties that are maintained by the LDAP into our app.

For example, show the Photo of the logged user:

Add the following method to your PersonController.groovy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class PersonController {
 
    def springSecurityService
 
    // PersonController CODE
 
    def photo = {
        def userDetails = springSecurityService.principal
        def photo = new File(GrailsResourceUtils.WEB_APP_DIR  + "/images/person.jpg").readBytes()
 
        if( userDetails.photo != null ){
            photo = userDetails.photo
        }
 
        response.outputStream << photo
        response.setHeader("Content-disposition", "attachment; filename=avatar.jpg")
        response.contentType = 'image/jpeg'
        response.outputStream << photo
        response.outputStream.flush()
        return;
 
    }
}

And modify the main.gsp to show the photo:

 

1
2
3
4
         <sec:ifLoggedIn>
          Hola <sec:loggedInUserInfo field="fullname"/> [<sec:loggedInUserInfo field="phone"/>] (<g:link controller="logout">Salir</g:link>)
          <img src="${createLink(controller:'person', action:'photo')}" width="40px" />
         </sec:ifLoggedIn>

 

Done!

 

This is how it looks:

That’s all…

Grails Rocks!

See you.

Escrito por alfonsorv

21 noviembre 2011 a las 11:01 pm

Escrito en codigo,grails,proyectos