RESTAPI用户注册

RESTAPI用户注册,api,grails,spring-security,Api,Grails,Spring Security,我创建了一个grailsrestapi 我使用的是Spring Security 用于创建用户和角色域类 grails s2-quickstart com.mycompany.myapp User Role 我的RESTAPI应该支持创建用户的能力,但我不知道如何做到这一点 @GrailsCompileStatic @EqualsAndHashCode(includes='username') @ToString(includes='username', includeNames=true,

我创建了一个grailsrestapi

我使用的是Spring Security

用于创建用户和角色域类

grails s2-quickstart com.mycompany.myapp User Role
我的RESTAPI应该支持创建用户的能力,但我不知道如何做到这一点

@GrailsCompileStatic
@EqualsAndHashCode(includes='username')
@ToString(includes='username', includeNames=true, includePackage=false)
class User implements Serializable {
    private static final long serialVersionUID = 1

    String username
    String password
    boolean enabled = true
    boolean accountExpired
    boolean accountLocked
    boolean passwordExpired

    User(String username, String password) {
        this()
        this.username = username
        this.password = password
    }

    Set<Role> getAuthorities() {
        (UserRole.findAllByUser(this) as List<UserRole>)*.role as Set<Role>
    }

    static constraints = {
        password nullable: false, blank: false, password: true
        username nullable: false, blank: false, unique: true
    }

    static mapping = {
        table '`user`'
        password column: '`password`'
    }
}
目前我可以创建用户,但不能自动为他们分配角色

在创建新用户时,如何将角色分配给它


我使用Grails 3.3.5

您可以这样做:

User user = new User(username: params.username, password: params.password).save()
Role role = Role.findOrSaveWhere(authority: "ROLE_USER")
new UserRole(user: user, role: role).save()

// If you want to assign another role to the user
role = Role.findOrSaveWhere(authority: "ROLE_SUBSCRIBED")
new UserRole(user: user, role: role).save()

如果您的项目只是一个RESTAPI,我建议您使用GrailsRESTAPI概要文件。这方面有一个很好的教程,您可以。

Spring Security Core通过实体UserRole和一系列静态方法委托管理用户和角色之间的关系,其中包括
create
,我与您分享定义

static UserRole create(User user, Role role, boolean flush = false) {
    def instance = new UserRole(user: user, role: role)
    instance.save(flush: flush)
    instance
}
正如您所看到的,这个静态方法需要两个参数:一个用户实例和一个角色实例,还可以选择flush。您可以通过以下方式使用此方法

Role adminRole = new Role(authority: 'ROLE_ADMIN').save() // here makes sense the recommendation of styl3r to first search if the role exists if it is not like that to create it

User testUser = new User(username: 'me', password: 'password').save()

UserRole.create testUser, adminRole
我从插件文档中获取了这个示例。在下面的链接中

Role adminRole = new Role(authority: 'ROLE_ADMIN').save() // here makes sense the recommendation of styl3r to first search if the role exists if it is not like that to create it

User testUser = new User(username: 'me', password: 'password').save()

UserRole.create testUser, adminRole