Grails Spring Security Core Create New User

Installed the latest spring-security-core plugin for grails 2.1.0, launched the user role s2-quickstart com.myapp, created the user role and domain UserRole, and then generated all com.myapp.User and com. myapp.Role build a basic CRUD. Now I'm trying to create a β€œRegister” button to allow new users to log in using the User create () method, the problem is that when creating a new user this happens without a role, I try to auto -assignate 'ROLE_USER' to every new user, which will register through the button and register form.

Any help or suggestion is appreciated.

+4
source share
3 answers

Add this to the controller action after verifying successful user creation:

def roleUser = Role.findByName('ROLE_USER') UserRole.create user, roleUser, true 
+5
source

I did something similar in one of my applications. I used

generate-all mypackage.User

The user was a class that extends SecUser (a domain object created by Spring Security Core). I am adding this code to UserController:

 def springSecurityService // injection of Spring Security def create() { def user = springSecurityService.getPrincipal() [userInstance: new User(params)] } def save() { def map=params def userInstance = new User(params) if (!userInstance.save(flush: true)) { render(view: "create", model: [userInstance: userInstance]) return } if (!userInstance.authorities.contains(SecRole.findByAuthority(params.role))) { SecUserSecRole.create userInstance, SecRole.findByAuthority(params.role) } flash.message = message(code: 'default.created.message', args: [message(code: 'user.label', default: 'User'), userInstance.id]) redirect(action: "show", id: userInstance.id) } 

In the BootStrap class, I made several roles:

 def springSecurityService def init = { servletContext -> def userRole = SecRole.findByAuthority('ROLE_USER') ?: new SecRole(authority: 'ROLE_USER').save(failOnError: true) def adminRole = SecRole.findByAuthority('ROLE_ADMIN') ?: new SecRole(authority: 'ROLE_ADMIN').save(failOnError: true) def moderatorRole = SecRole.findByAuthority('ROLE_MODERATOR') ?: new SecRole(authority: 'ROLE_MODERATOR').save(failOnError: true) } 

In the user / _form.gsp template, I added this selection to select a role and send it to params

 <sec:ifAllGranted roles="ROLE_ADMIN"> <g:select name="role" from="${['ROLE_USER', 'ROLE_MODERATOR', 'ROLE_ADMIN']}" value='ROLE_MODERATOR'/> </sec:ifAllGranted> <sec:ifNotLoggedIn> <div class="hidden"><g:textField name="role" value="ROLE_USER"/></div> </sec:ifNotLoggedIn> 
+4
source

You can use this code:
Add this to the controller action after verifying successful user creation:

 def userr = user.save flush:true UserRole.create userr, roleUser.findByAuthority('ROLE_USER'), true 
0
source

All Articles