我一直在做这样的事情在我的应用程序之一。我用
产生,所有mypackage.User
用户是类扩展SecUser(Spring Security的核心创建的域对象)。 我这个代码添加到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)
}
在引导类我做了一些角色:
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)
}
在用户/ _form.gsp模板我已经添加了这个选择,选择角色和发送它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>
来源
2013-01-30 09:14:25
kmb
目前,我通过缺省提供注册由view.gps创建从用户控制器的方法,使用 <克:建立连结控制器=“用户” action =“create”> 那么如何以及在何处捕捉用户创建以及我应该在哪里获得新的UserRole? – smace 2012-07-27 14:55:54
听起来像你正在使用动态脚手架 - 切换到静态(使用'generate-controller'或'generate-all'脚本)并编辑'create'控制器动作。 – 2012-07-27 15:26:08
请注意,我不得不使用'Role.findByAuthority('ROLE_USER')'而不是'Role.findByName('ROLE_USER')' – 2015-09-07 12:06:05