休息APi用户注册

时间:2018-05-12 18:36:59

标签: api grails spring-security

我创建了一个Grails REST API

我正在使用Spring Security

用于创建用户和角色域类

grails s2-quickstart com.mycompany.myapp User Role

我的REST API应该支持创建用户的能力,但我不知道如何做到这一点

@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`'
    }
}

我创建了一个控制器

class UserController extends RestfulController {
    static responseFormats = ['json', 'xml']
    UserController() {
        super(User)
    }

    @Secured(['permitAll'])
    @Override
    def save() {
        super.save()
    }
}

目前我可以创建用户,但我不能自动为他们分配角色

如何在创建新用户时为其分配ROLE_USER的角色?

我使用Grails 3.3.5

2 个答案:

答案 0 :(得分:0)

您可以这样做:

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()

如果您的项目仅是REST API,我建议您使用Grails rest-api配置文件。有一个很好的教程,你可以check it out here

答案 1 :(得分:0)

Spring Security Core通过实体UserRole委托管理User和Role之间关系的责任,其中包含一系列静态方法create,我与大家分享定义

static UserRole create(User user, Role role, boolean flush = false) {
    def instance = new UserRole(user: user, role: role)
    instance.save(flush: flush)
    instance
}

如您所见,此静态方法需要两个参数:User实例和角色实例,并可选择刷新。您可以通过以下方式使用此方法

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

我从插件文档中提取了这个例子。在以下链接中。

https://grails-plugins.github.io/grails-spring-security-core/3.2.x/index.html#tutorials