[英]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.