[英]Rest APi User Registration
我创建了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
您可以执行以下操作:
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配置文件。 有一个很好的教程,您可以在这里查看 。
Spring Security Core通过实体UserRole委托使用一系列静态方法(其中包括create
来管理用户和Role之间的关系的职责,我与您分享定义
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实例,并且可以选择刷新。 您可以通过以下方式使用此方法
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.