.:: CODE SNIPPET ::.

"Your time is limited, so don't waste it living someone else's life"

Configure spring security with ldap authentication and local system roles in grails


Add plugins Add plugins of Spring security and ldap in BuildConfig

plugins {
        compile ":spring-security-core:2.0-RC4"
        compile ":spring-security-ldap:2.0-RC2"
    }

Configure spring security
Configure spring security and LDAP authentication in Config


// ------------------ -------------------------------------------- //
// ------------------ SPRING SECURITY CONFIG --------------------- //
grails.plugin.springsecurity.providerNames=['ldapAuthProvider']
// ------------------ LDAP SERVER CONFIG ------------------------- //
grails.plugin.springsecurity.ldap.context. managerDn = 'uid=ldapread_sw,ou=Services,dc=dcname,dc=vn'
grails.plugin.springsecurity.ldap.context. managerPassword = 'secret'
grails.plugin.springsecurity.ldap.context. server = 'yourldapserver'

grails.plugin.springsecurity.ldap.authorities. groupSearchBase = 'dc=dcname,dc=vn'
grails.plugin.springsecurity.ldap.search. base = 'dc=dcname,dc=vn'
grails.plugin.springsecurity.ldap.useRememberMe = false
grails.plugin.springsecurity.ldap.authorities.retrieveGroupRoles = true
grails.plugin.springsecurity.ldap.authorities.retrieveDatabaseRoles = true
grails.plugin.springsecurity.ldap.search.attributesToReturn = ['mail', 'displayName']
grails.plugin.springsecurity.ldap.authorities.prefix = 'ROLE_'
//grails.plugin.springsecurity.ldap.mapper.userDetailsClass='minhht.vn.grailstudy.security.User'

// ------------------ PERSSIMISTIC CONFIG ------------------------- //
grails.plugin.springsecurity.rejectIfNoRule = true
grails.plugin.springsecurity.fii.rejectPublicInvocations = false

// ------------------ SECURITY CONFIG TYPE ----------------------- //
grails.plugin.springsecurity.securityConfigType = "InterceptUrlMap"//"Annotation"
//grails.plugin.springsecurity.controllerAnnotations.staticRules = [
//    '/':                              ['permitAll'],
//    '/index':                         ['permitAll'],
//    '/index.gsp':                     ['permitAll'],
//    '/assets/**':                     ['permitAll'],
//    '/**/js/**':                      ['permitAll'],
//    '/**/css/**':                     ['permitAll'],
//    '/**/images/**':                  ['permitAll'],
//    '/**/favicon.ico':                ['permitAll'],
//    '/login/**':                      ['permitAll'],
//    '/logout/**':                     ['permitAll']]

grails.plugin.springsecurity.roleHierarchy = '''
   ROLE_ADMIN > ROLE_SUPER_USER
   ROLE_SUPER_USER > ROLE_USER
'''
grails.plugin.springsecurity.successHandler.defaultTargetUrl = '/'
grails.plugin.springsecurity.successHandler.alwaysUseDefaultTargetUrl=true

// Added by the Spring Security Core plugin:
//grails.plugin.springsecurity.userLookup.userDomainClassName = 'minhht.vn.grailstudy.secure.User'
//grails.plugin.springsecurity.userLookup.authorityJoinClassName = 'minhht.vn.grailstudy.secure.UserRole'
//grails.plugin.springsecurity.authority.className = 'minhht.vn.grailstudy.secure.Role'
//grails.plugin.springsecurity.controllerAnnotations.staticRules = []
// ------------------ INTERCEPT URL MAP CONFIG ------------------- //

grails.plugin.springsecurity.interceptUrlMap = [
    '/':                              ['ROLE_USER'],
    '/index.gsp':                     ['ROLE_USER'],
    '/assets/**':                     ['permitAll'],
    '/**/js/**':                      ['permitAll'],
    '/**/css/**':                     ['permitAll'],
    '/**/images/**':                  ['permitAll'],
    '/**/favicon.ico':                ['permitAll'],
    '/login/**':                      ['permitAll'],
    '/logout/**':                     ['permitAll'],
    '/grails-errorhandler':           ['permitAll'],

    '/contact/create':                ['ROLE_ADMIN'],
    '/contact/save/**':               ['ROLE_ADMIN'],
    '/contact/edit/**':               ['ROLE_SUPER_USER'],
    '/contact/update/**':             ['ROLE_SUPER_USER'],
    '/contact/show/**':               ['ROLE_USER'],
    '/contact/index':                 ['ROLE_USER'],

    '/user/**':                       ['ROLE_SUPER_USER'],
    '/customer/**':                   ['ROLE_USER'],
    '/contact/**':                    ['ROLE_SUPER_USER'],
    '/user/**':                       ['ROLE_ADMIN'],
    '/role/**':                       ['ROLE_ADMIN']]

Implement authorities Implement the authority for user


class AuthoritiesPopular implements LdapAuthoritiesPopulator
{
    /** The Constant ATT_FULLNAME. */
    private static final String ATT_FULLNAME = "displayName"

    /** The Constant ATT_EMAIL. */
    private static final String ATT_EMAIL = "mail"

    /** The Constant ATT_EMPLOYEE_ID. */
    private static final String ATT_EMPLOYEE_ID = "employeeNumber"


    /**
     * {@inheritDoc}
     *
     * @see org.springframework.security.ldap.userdetails.LdapAuthoritiesPopulator#getGrantedAuthorities(org.springframework.ldap.core.DirContextOperations, java.lang.String)
     */
    @Override
    public Collection<? extends GrantedAuthority> getGrantedAuthorities(
            final DirContextOperations context,
            final String username)
    {
        def user=null
        def mapAttributes=new HashMap<String, String>()

        extractAttributes(context, mapAttributes)
        User.withTransaction
        {
            user = User.findByUsername(username)
            if(mapAttributes!=null)
            {
                user.fullName=mapAttributes.get(ATT_FULLNAME)
                user.email=mapAttributes.get(ATT_EMAIL)
                user.employeeId=mapAttributes.get(ATT_EMPLOYEE_ID)
                try
                {
                    user.save()
                } catch (Exception e)
                {
                    e.printStackTrace()
                }
            }

            return user.getAuthorities().toList()
        }
    }

    /**
     * Extract attributes.
     *
     * @param context the context
     * @param mapAttributes the map attributes
     */
    private void extractAttributes(final DirContextOperations context, final Map<String, String> mapAttributes)
    {
        def attributes = context.getAttributes()
        def allAttributes = attributes.getAll()
        def name,value
        while(allAttributes.hasMoreElements())
        {
            Attribute attribute = allAttributes.nextElement()
            try
            {
                name = attribute.getID()
                value = attribute.get(0).toString()
                if ((name != null) && (value != null))
                {
                    mapAttributes.put(name, value)
                }
            }
            catch (NamingException e)
            {
                e.printStackTrace()
            }
        }
    }
}

Add your first user When start up your web application you also need to create the first user to verify your spring security configuration and create other user. Hence, in Bootstrap configuration file, you add your first user Add system role


def lstPreDefinedRoles=[
    'ROLE_ADMIN',
    'ROLE_SUPER_USER',
    'ROLE_USER'
]

if(Role.count()<lstPreDefinedRoles.size())
{
    lstPreDefinedRoles.each
    {
        new Role(authority:it).save(flush:true)
    }
    assert Role.count == lstPreDefinedRoles.size()
}

add user

if(User.count()<=0)
{
    User admin=new User()
    admin.username="thminh_1"
    def lstAdminRoles=new ArrayList<Role>()
    def defaultAdminRole=Role.findByAuthority('ROLE_SUPER_USER')
    lstAdminRoles.add(defaultAdminRole)
    if (defaultAdminRole!=null)
    {
        admin.authorities=lstAdminRoles
    }
    admin.save()
}
assert User.count() >= 1
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: