Skip to main content

Creating an email authentication provider in Grails with Acegi plugin

Posted by brunogh on April 8, 2010 at 9:56 PM PDT

A long time without blogging, I have been busy working with DTV applications and GRails... this post goes with the second topic...

Have you already installed Spring Security (Acegi) plugin in Grails? Do you want to allow logins with the email also - like Twitter, SlideShare, etc - and not only with the default username?

Here is the simple way to make it to work:

1 - Implement an AuthenticationProvider (EmailAuthenticationProvider) in src/groovy:

import org.codehaus.groovy.grails.
import User

class EmailAuthenticationProvider implements AuthenticationProvider {

    def authenticateService

    Authentication authenticate(Authentication customAuth) {
               User.withTransaction { status ->
                    User user = User.findByEmail(customAuth.
                    if(user) {
                        if (user?.passwd == authenticateService.
encodePassword(customAuth.credentials)) {
                            GrantedAuthorityImpl[] authorities = user.authorities.collect {new GrantedAuthorityImpl(it.
                            def userDetails = new GrailsUserImpl(, user.passwd, true, true, true, true, authorities, user)
                            def token = new UsernamePasswordAuthentication
Token(userDetails, user.passwd, userDetails.authorities)
                            token.details = customAuth.details

                            return token
                        }else throw new BadCredentialsException("Log in failed - identity could not be verified");
                    }else {
                        return null

    boolean supports(Class authentication) {
        return true

2 - Set this provider bean in grails-app/conf/spring/resources.xml file:

import EmailAuthenticationProvider
beans = {
     emailAuthenticationProvider(EmailAuthenticationProvider) {
        authenticateService = ref("authenticateService")

3 - Add your email provider in the stack in grails-app/conf/SecurityConfig.groovy fi(DaoAuthenticationProvider is the default one that uses the username):

providerNames = ['emailAuthenticationProvider', daoAuthenticationProvider','anonymousAuthenticationProvider', 'rememberMeAuthenticationProvider']


4 - Done! Try now to login with the username or email.


Have fun!

Bruno Ghisi

ps: Felipe Gaúcho, you were a brilliant guy. We are going to miss you.

Related Topics >>