我正在尝试使用spring security core 3.0.4创建一个带有grails 3.1.2的网站。
我使用过这个页面: Grails Spring Security Core
我使用了以下脚本(将“website”替换为我的项目名称):
grails s2-quickstart com.website User Role
grails s2-create-persistent-token com.website.PersistentLogin
grails s2-create-role-hierarchy-entry com.website.RoleHierarchyEntry
然后我将以下内容添加到我的BootStrap.groovy:
if(User.count()==0) {
Date testDate = new Date()
Role userRole = new Role('ROLE_USER').save()
Role adminRole = new Role('ROLE_ADMIN').save()
User user = new User("John","password").save()
User admin = new User("Richard","password").save()
UserRole.create(admin, adminRole)
UserRole.create(user, userRole)
UserRole.withSession {
it.flush()
it.clear()
}
assert User.count() == 2
assert Role.count() == 2
assert UserRole.count() == 2
}
我收到一条关于无法找到User bean类权限的错误,所以我用这个替换了getAuthorities方法(因为将它添加到临时列表不起作用):
Set<Role> getAuthorities() {
if(this.id){
return UserRole.findAllBySecUser(this)*.role
}
else{
return [] as Set
}
}
然后我再次尝试构建,并收到有关UserRole类的异常。
ERROR org.springframework.boot.SpringApplication - Application startup failed
org.codehaus.groovy.runtime.metaclass.MethodSelectionException: Could not find which method <init>() to invoke from this list:
public com.website.UserRole#<init>(org.springsource.loaded.C)
public com.website.UserRole#<init>(com.website.User, com.website.Role)
at groovy.lang.MetaClassImpl.chooseMethodInternal(MetaClassImpl.java:3197) ~[groovy-2.4.6.jar:2.4.6]
at groovy.lang.MetaClassImpl.chooseMethod(MetaClassImpl.java:3134) ~[groovy-2.4.6.jar:2.4.6]
at groovy.lang.MetaClassImpl.createConstructorSite(MetaClassImpl.java:3434) ~[groovy-2.4.6.jar:2.4.6]
at org.codehaus.groovy.runtime.callsite.CallSiteArray.createCallConstructorSite(CallSiteArray.java:91) [groovy-2.4.6.jar:2.4.6]
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallConstructor(CallSiteArray.java:60) [groovy-2.4.6.jar:2.4.6]
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:235) [groovy-2.4.6.jar:2.4.6]
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:247) [groovy-2.4.6.jar:2.4.6]
at com.website.UserRole.create(UserRole.groovy:55) ~[main/:na]
如何解决他的错误?我不知道这个特殊错误意味着什么:/
答案 0 :(得分:3)
看起来用户有验证错误但没有保存。您正在使用2-arg构造函数,但如果需要的属性多于用户名和密码,则验证将失败,save()
将返回null。
如果您更改代码以创建用户
User user = new User(..., ...)
user.save()
if (user.hasErrors()) {
println user.errors
}
那么你会看到什么是错的。在构造函数调用后添加缺少的属性:
User user = new User(..., ...)
user.fullName = '...'
或切换到传统的Map构造函数,将其初始化为一行:
User user = new User(username: ..., password: ..., fullName: ...)