3

In pure spring I can do like this

<security:authentication-manager>
<security:authentication-provider user-service-ref="customUserDetailsService">       
    <security:password-encoder ref="passwordEncoder"/>
</security:authentication-provider>
<security:authentication-provider>
    <security:user-service>
        <security:user name="admin" password="admin" authorities="ROLE_USER, ROLE_ADMIN" />
    </security:user-service>

Is it any way to do the same in Grails with Spring Security plugin?

I can implement my own authentication-provide but in this case I will store credentials hardcoded in class.

5 Answers 5

2

You can do it by using InMemoryUserDetailsManager (in resources.groovy):

import org.springframework.security.provisioning.InMemoryUserDetailsManager
import org.springframework.security.core.userdetails.User
import org.springframework.security.core.authority.SimpleGrantedAuthority

beans = {
    userDetailsService(InMemoryUserDetailsManager,
            [new User('admin', 'password hash', [new SimpleGrantedAuthority('ROLE_ADMIN')])])
}
1
1

Typically this is done in BootStrap.groovy, e.g.

import com.foo.Role
import com.foo.User
import com.foo.UserRole

class BootStrap {

   def init = {
      def userRole = Role.findOrSaveByAuthority('ROLE_USER')
      def adminRole = Role.findOrSaveByAuthority('ROLE_ADMIN')

      if (!User.findByUsername('admin')) {
         def admin = new User(username: 'admin', password: 'admin').save()

         UserRole.create admin, userRole
         UserRole.create admin, adminRole

         User.withSession { it.flush() }
      }
   }
}
0

This link contains an example where you can leverage InMemoryUserDetailsManager and the BooStrap.groovy to create users.

Here is what I have in BootStrap.groovy (I'm loading the password from environment variables in this case):

import org.springframework.security.provisioning.UserDetailsManager
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.security.core.userdetails.User
import org.springframework.security.core.userdetails.UserDetails

class BootStrap {

    UserDetailsManager userDetailsService

    def init = { servletContext ->

        UserDetails user1 = new User('user1', "${System.getenv("USER1_PWD")}", [new SimpleGrantedAuthority('ROLE_USER')])
        userDetailsService.createUser(user1)

        UserDetails user2 = new User('user2', "${System.getenv("USER2_PWD")}", [new SimpleGrantedAuthority('ROLE_USER')])
        userDetailsService.createUser(user2)

    }
    def destroy = {
    }
}

and here is my resources.groovy

import org.springframework.security.provisioning.InMemoryUserDetailsManager
import org.springframework.security.authentication.encoding.PlaintextPasswordEncoder

beans = {

    userDetailsService(InMemoryUserDetailsManager,[])
    passwordEncoder(PlaintextPasswordEncoder)
}
0

Realization of Bootstrapping "default" User, using our DomainService(see below)

import grails.gorm.transactions.Transactional

import org.grails.datastore.gorm.GormEntity

import java.util.function.Supplier

class DomainService {

@Transactional
<T extends GormEntity> T createIfNotExists(Supplier<T> existingFinder, Supplier<T> newInstance) {
    T model = existingFinder.get()
    if (!model) {
        model = newInstance.get()
        model.save()
    }
    model
}

}

class BootStrap {

def grailsApplication

def domainService

def init = { servletContext ->

    log.info 'BOOTSTRAPPING start'

    createSuperAdminIfNotExist()

    log.info 'BOOTSTRAPPING end'

}

def destroy = {
}

void createSuperAdminIfNotExist() {
    def superAdminProperties = grailsApplication.config.academy.user.super_admin

    domainService.createIfNotExists({ AcademyAdmin.findByEmail(superAdminProperties.email) },
            {
                new AcademyAdmin(
                        createdOn: new Date(),
                        name     : superAdminProperties.name,
                        surname  : superAdminProperties.surname,
                        email    : superAdminProperties.email,
                        password : superAdminProperties.password,
                        passwordConfirm: superAdminProperties.password
                )
            })
}

}

-1

You can use these custom tags provided by grails spring security.

<sec:ifLoggedIn>
<li><a><sec:username /></a></li>
<li><g:link controller="logout">Logout</g:link></li>
</sec:ifLoggedIn>
<sec:ifNotLoggedIn>
<li><g:link controller='controller' action='action'>Login</g:link></li>
<li><g:link controller="controller" action="action">Signup</g:link></li>
</sec:ifNotLoggedIn>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.