Monthly Archives: October 2014

LDAP Authentication and DB authorisation with Grails Spring Security

Recently I faced quite simple problem – allow application to authenticate users via LDAP but authorise them via database. It is a common solution – we make sure that only company’s users are logging into app, but there comes flexibility with ACL stored locally. In Grails it looked pretty simple until I started to integrate this solution into my application. It took me a while to put everything together so I decided to share it.

To make long things short – there is an offical documentation but IMHO, it should be tweaked a little to be more user-friendly. The most important thing to understand are sides and roles that take place in logging process. There is LDAP instance, where we send requests to authorise user. LDAP response must be transmitted to our app and full our users’ object. Meanwhile there is also roles read from database. In addition there is simple check – if logging user has no account in our app, we will create it with default roles.

My app uses simple domain classes provided by Spring Security (User, Role and UserRole). If You are not familiar with them I suggest reading official docs. First we create UserMappingDetails class, which is simple POJO that will store user data (login, password, account data) and authorities (roles that user has).

class ChlebikUserDetails extends GrailsUser {

   ChlebikUserDetails(String username, String password, boolean enabled,
                 boolean accountNonExpired, boolean credentialsNonExpired,
                 boolean accountNonLocked,
                 Collection<GrantedAuthority> authorities,
                 long id, String fullName) {
      super(username, password, enabled, accountNonExpired,
            credentialsNonExpired, accountNonLocked, authorities, id)      
   }
}

Next we create mapping class, which will translate LDAP response to our application user.

class ChlebikUserDetailsContextMapper implements UserDetailsContextMapper {

	private static final List NO_ROLES = [new SimpleGrantedAuthority(SpringSecurityUtils.NO_ROLE)]
		
	@Override
	@Transactional
	public ChlebikUserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<SimpleGrantedAuthority> authority) {
		
		User user = User.findByUsername(username)
		
		if(!user) {					
				// Create new user and save to the database                                
				user = new User()
				user.username = username				
				user.password = "123" // doesn't matter
				user.save(flush: true, failOnError: true)
									
				UserRole userRole = new UserRole()
				userRole.user = user
				userRole.role = Role.findByAuthority('USER') // Default role in my app
				userRole.save(flush: true, failOnError: true)			
		}
						 
		def authorities = user.getAuthorities().collect { new SimpleGrantedAuthority(it.authority) }		
		def userDetails = new ChlebikUserDetails(username, user.password, user.enabled, false,
					false, false, authorities, user.id, username)
		return userDetails
	}

	
	@Override
	public void mapUserToContext(UserDetails arg0, DirContextAdapter arg1) {}	
}

Ok, we are getting closer. Last class to create is service that will be called by Spring Security to retrieve our user when needed. It cannot be put in Grails’ service directory!!! Just place it in src/groovy

class PrePopulateUserDetailsService implements GrailsUserDetailsService  {
	
	Logger logger = Logger.getLogger(getClass())
	LdapUserDetailsService ldapUserDetailsService
	
	static final List NO_ROLES = [new SimpleGrantedAuthority(SpringSecurityUtils.NO_ROLE)]
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
		return loadUserByUsername(username, true)
	}
	
	@Override
	@Transactional	// Services in Grails are transactional by default but it is normal class so we put this annotation
	public UserDetails loadUserByUsername(String username, boolean loadRoles) throws UsernameNotFoundException, DataAccessException {
				
		User user = User.findByUsername(username)
		def authorities = user.getAuthorities().collect {new SimpleGrantedAuthority(it.authority)}
		
		return new ChlebikUserDetails(user.username, user.password, user.enabled,
			!user.accountExpired, !user.passwordExpired,
			!user.accountLocked, authorities ?: NO_ROLES, user.id,
			user.username)   
	}
}

That’s all. Of course we need to add some config to our application. First we visit configuration folder and spring subfolder. There in resources.groovy we put this (registering beans):

beans = {		
	ldapUserDetailsMapper(com.wordpress.chlebik.ChlebikUserDetailsContextMapper)
	userDetailsService(com.wordpress.chlebik.PrePopulateUserDetailsService)
}

And in out Config.groovy (or whatever user-defined config file You are using) we should have several config properties. I am putting them all (to allow Grails connect to LDAP).

grails.plugin.springsecurity.providerNames = ['rememberMeAuthenticationProvider', 'ldapAuthProvider', 'anonymousAuthenticationProvider']

// Probably better to keep this data in an external file for security reasons
grails.plugin.springsecurity.ldap.context.managerDn = ''
grails.plugin.springsecurity.ldap.context.managerPassword = ''
grails.plugin.springsecurity.ldap.context.server = ''

grails.plugin.springsecurity.ldap.authorities.ignorePartialResultException = true // typically needed for Active Directory
grails.plugin.springsecurity.ldap.search.base = 'CN=putwhatyoumust,O=putwhatyoumust'
grails.plugin.springsecurity.ldap.authenticator.dnPatterns=='uid={0},CN=putwhatyoumust,O=putwhatyoumust'
grails.plugin.springsecurity.ldap.search.filter="uid={0}" 
grails.plugin.springsecurity.ldap.search.searchSubtree = true
grails.plugin.springsecurity.ldap.auth.hideUserNotFoundExceptions = false

// These are crucial for LDAP/DB configuration
grails.plugin.springsecurity.ldap.mapper.userDetailsClass='com.wordpress.chlebik.ChlebikUserDetails'
grails.plugin.springsecurity.ldap.authorities.retrieveGroupRoles = false
grails.plugin.springsecurity.ldap.authorities.retrieveDatabaseRoles = true

And it magically works. Above code is the result of several hours on the web. Below I put all links that helped me a lot.

Grails passwords salted
Juan Vazquez GitHub
Most helpfull Nabble
Customizing authentication in your grails app
Official plugin page

Groovy 2.3.5 backward compatibility with Spock unit tests

In my new workplace there is a problem – corporate firewall, which is a common problem in IT world. Therefore update sites of Eclipse are blocked, which means quite a mess with dependencies and plugin management.

My main concern was Spock, which I have run using built-in Groovy in version 2.3.6, while tests and whole application was written in Grails 2.2.3 with Groovy a little bit older 😉 Finally it came to my attention that hated exception

Caused by: java.lang.ClassNotFoundException: org.codehaus.groovy.runtime.typehandling.ShortTypeHandling at java.net.URLClassLoader$1.run(URLClassLoader.java:372)

can be easily fixed in a way that Guillaume Laforge wrote. Just downloaded JAR, added to project’s classpath and there it is – my Spock test are working like charm.

Welcome back Grails

I started my journey with learning Java web-frameworks with Grails. That was really long time ago (around 2009) with Grails’ version 1.0.4. When I became full-time Java programmer I used Grails in several internal CRUD apps, but it was quick&dirty solution to provide basic functionality. My new job (I’ve just started) involves mainly programming with Groovy&Grails therefore I’ve decided to write a few posts about what is going on in Groovy&Grails world right now.

grails Before I start there is a big announcement. As Graeme Rocher posted on Twitter, new version of Grails (starting with number 3) will be totally new thing – based on Spring Boot and many projects around it. Therefore Grails being described here is going to retire in a predictable future. Just so You know.

The latest version of Grails which I am using is 2.4.3 with Groovy in version 2.3. In a following article I am gonna to point out some problems and interesting things I have discovered while ‘getting in touch’ with latest Grails.

Scaffolding

Scaffolding is often presented as one of the most ‘groovy’ thing in Grails. The ability to quickly prototype working application is powerful feature and it was a place where I started my revisit. And right at the beginning I have encountered an subtle problem. Reference documentation says that there is a possibility to run such code:

class UserController {
     static scaffold = true     
}

And it should work with existing User domain class. I have given it a try but I was unsuccessfull. Why? Grails complained about missing domain class. What have I done wrong? The problem is with packaging – I have never liked examples using default package. With Grails it is even more problematic as there are separate folders for controllers, domain classes and so on. Therefore as I created com.wordpress.chlebik.grails.tutorial package inside domain folder, framework could not resolve proper path. The solution is simple – just use full class name.

class UserController {
     static scaffold = com.wordpress.chlebik.grails.tutorial.User
}

It works like a charm. It is also possible to use such code to enable scaffolding for a given domain class even from controllers with different name:

class AdminController {
     static scaffold = com.wordpress.chlebik.grails.tutorial.User
}

In my opinion Grails scaffolding is even better than it was with feature called static scaffolding. Back in 2009 scaffolding was interesting, but it was done as a ‘runtime magic’. There was no way to interact with generated sources (or it was not so easy). Right now we have static scaffolding which is scaffolding but with generated sources. Imagine creating simple domain class like User

class User {

    static constraints = {}
	
    String       firsrName
    String       lastName	
    String       email	
	
}

Using Grails console or IDE support we can invoke command:

grails generate-all User

which creates separate views (I mean GSP files) and controller with implemented methods. What is more cool, are test classes (based on Spock specifications) generated as well with testing logic within! So if You are not familiar with unit-testing – it is a great place to learn how it is done.

Testing

A few years ago my knowledge about TDD was almost non-existent. It has changed since then, therefore I welcomed Grails’ testing support pretty great. As I mentioned above, we can be given out-of-the-box tests methods with logic in them. Of course it is not what TDD is about, but it makes a good start to make changes and go further. What is more interesting is use of mixins. They provide simple way to link tested class with tests itseslf. What is more cool is use of Spock testing framework. I have to admit I have a problem with finding which plugin/core functionality provides Spock as a dependency. There is Spock Grails Plugin but I do not see any dependencies to it in plain configuration files.

But enough of it – we have Spock at our service, so using it is very simple. Just like this:

@TestFor(UserController)
class UserControllerSpec extends Specification {

    def setup() {
    }

    def cleanup() {
    }

    void "test something"() {
    }
}

If You are trying to run above test it is possible You get initializationError. Test method must atually test something – leaving empty method body is not an option!

We are given several implicit objects like request, response, controller, view to support controller testing. We can use very straightforward annotation @Mock – which just instantiates in-memory GORM which mocks all ORM-related calls. There is also possiblity to run integration tests, and what is even more cool – even more plugin for functional tests. Back in time there was only Canoo available, now new solutions like Selenium and Geb are also an option. It is hard to write here all about testing in Grails. I am planning to wrote more in separate posts.

Config options

Config files are still very neat way to tail application to our needs. What is the most important change since I last worked with Grails is added BuildConfig.groovy file, which was designed to separate configuration of build process and application config itself. What is more fabulous is logging configuration – so many customizing possibilities! To keep things short I am planning also some kind of post about it, but there is a nice place to start.

Asset Pipeline Plugin

As a Java programmer I am not keeping up with latest changes in HTML&CSS&JavaScript community. There has been tremendous progress in that areas lately (not to mention HTML5, LESS&SASS, writing MVP apps in JavaScript). Therefore creators of Grails are trying to simplify several things so they have switched from resources-plugin to asset-pipeline-plugin.

With previous approach, all resources put in web-app folder were just laying there waiting for the programmer to use them. It was a matter of view layer to include or exclude used resources. Right now plugin has possibility to include or exclude portions of CSS or JavaScript used on certain page. Another cool thing is ability to automaticaly apply changes in resources code while in development mode. there is a great Youtube video about it.

Static compilation

Somewhere by the road to Groovy 2.0 and Java 7 appeared static compilation and invoke dynamic. To make long things short – in a situation where You do not need dynamic Groovy features, it is possible to disable them and gain boost on performance. There are is nice blog post worth mentioning.

Summary

As I walk through the latest reference documentation I constantly see something new. It is hard to put everything in one blog post therefore I am planning several additional articles about latest Grails and Groovy combo. Stay tuned.

Knock knock! Who is there? Chlebik in English…

Yep, the time has come, my blog will be – as of this moment – written only in English.

keep-calm Switching languages is not a simple thing, but lately I’ve realised, that my skills and experience have grown a little since 2008 when I started blogging and I need some new challenges. There are many great blogs and programming sites on the internet (unfortunately – in English) and I want to be a part of it. Writing only in Polish (which was a great decision back in 2008) now is somehow limiting.

I keep all my archives as they were – in Polish – main pages descriptions will also not be translated. Blog’s interface should be changed to English by the time You are reading this note. From this day all my posts are gonna be written in English. It is not my native language so I am asking my readers to forgive me if any mistakes appear.