我在Grails 2.4.4上,使用Spring Security Core 2.0-RC4,Spring Security REST 1.5.0.M1和Spock 0.7功能。
我正在使用功能测试来测试构建REST API的控制器。设置测试后,我会创建一个User
,一个管理员Role
,然后创建一个UserRole
。当我检查User
是否已使用spock功能测试的INSIDE的相应凭据持久保存时,我发现一切正常。
但是,在进行身份验证时,GormUserDetailsService
在调用User.findWhere(username:<appropriate username>)
时不会产生任何结果。具体方法来自GormUserDetailsService
:
UserDetails loadUserByUsername(String username, boolean loadRoles) throws UsernameNotFoundException {
def conf = SpringSecurityUtils.securityConfig
String userClassName = conf.userLookup.userDomainClassName
def dc = grailsApplication.getDomainClass(userClassName)
if (!dc) {
throw new IllegalArgumentException("The specified user domain class '$userClassName' is not a domain class")
}
Class<?> User = dc.clazz
User.withTransaction { status ->
def user = User.findWhere((conf.userLookup.usernamePropertyName): username)
if (!user) {
log.warn "User not found: $username"
throw new NoStackUsernameNotFoundException()
}
Collection<GrantedAuthority> authorities = loadAuthorities(user, username, loadRoles)
createUserDetails user, authorities
}
}
问题是User.findWhere()
来电没有找到任何内容,即使我已经在功能测试中确认我已将用户实例刷新到数据库中。我已尝试使用此方法的UserRole
块内的所有User
和findAll()
进行withTransaction
调用,但它们仍未返回任何内容。
有人有什么想法吗?我应该嘲笑一些我不是吗?我在功能测试中使用@TestFor
和@Mock
注释。
更新
以下是我的功能测试的简单版本:
package com.help
import grails.plugins.rest.client.RestBuilder
import grails.plugins.rest.client.RestResponse
import grails.test.mixin.Mock
import grails.test.mixin.TestFor
import groovy.json.JsonBuilder
import org.codehaus.groovy.grails.web.json.JSONObject
import spock.lang.Shared
import spock.lang.Specification
@TestFor(PersonController)
@Mock([Person, Role, PersonRole])
class PersonControllerSpec extends Specification {
@Shared
RestBuilder rest = new RestBuilder(connectTimeout:10000, readTimeout:20000)
@Shared
String baseUrl = "http://localhost:8080"
@Shared
int iterationCount = 0
Collection<Person> persons = []
def setup() {
Role adminRole = Role.findByAuthority("ROLE_ADMIN") ?: new Role(authority:"ROLE_ADMIN").save(failOnError:true, flush:true)
Role userRole = Role.findByAuthority("ROLE_USER") ?: new Role(authority:"ROLE_USER").save(failOnError:true, flush:true)
Person admin = new Person(name:"reserved", keyword:"admin", password:"password", email:"email@email.com", phone:"2222222222", personalPhoneNumber:"1112223333").save(failOnError:true, flush:true)
Person user = new Person(name:"reserved", keyword:"user", password:"password", email:"email@email.com", phone:"2222222222", personalPhoneNumber:"1112223333").save(failOnError:true, flush:true)
PersonRole.create(admin, adminRole, true)
PersonRole.create(user, userRole, true)
for (i in 0..20) {
persons << new Person(name:"person-$iterationCount-$i", password:"password", keyword:"p-$iterationCount-$i", email:"email@email.com", phone:"1112223333", personalPhoneNumber:"1112223333")
}
persons*.save(failOnError:true, flush:true)
}
def cleanup() { iterationCount++ }
void "test listing persons"() {
when: "we have an authenticated request"
JsonBuilder jsonBuilder = new JsonBuilder()
JSONObject json = jsonBuilder keyword:"admin", password: "password"
RestResponse authResponse = rest.post("$baseUrl/api/login") {
contentType "application/json"
body(json)
}
then: "can access both restricted and public resources"
...
}
}
以下是Config.groovy
中的弹簧安全设置:
grails.plugin.springsecurity.userLookup.userDomainClassName = 'com.help.Person'
grails.plugin.springsecurity.userLookup.usernamePropertyName = 'keyword'
grails.plugin.springsecurity.userLookup.authorityJoinClassName = 'com.help.PersonRole'
grails.plugin.springsecurity.authority.className = 'com.help.Role'
grails.plugin.springsecurity.controllerAnnotations.staticRules = [
'/': ['permitAll'],
'/index': ['permitAll'],
'/index.gsp': ['permitAll'],
'/assets/**': ['permitAll'],
'/**/js/**': ['permitAll'],
'/**/css/**': ['permitAll'],
'/**/images/**': ['permitAll'],
'/**/favicon.ico': ['permitAll'],
'/dbconsole/**': ['ROLE_USER', 'ROLE_ADMIN']
]
grails.plugin.springsecurity.filterChain.chainMap = [
'/v1/public/**': 'anonymousAuthenticationFilter,restTokenValidationFilter,restExceptionTranslationFilter,filterInvocationInterceptor',
'/v1/**': 'JOINED_FILTERS,-anonymousAuthenticationFilter,-exceptionTranslationFilter,-authenticationProcessingFilter,-securityContextPersistenceFilter,-rememberMeAuthenticationFilter', // v1 rest api stateless
'/api/**': 'JOINED_FILTERS,-anonymousAuthenticationFilter,-exceptionTranslationFilter,-authenticationProcessingFilter,-securityContextPersistenceFilter,-rememberMeAuthenticationFilter', // api utility methods stateless
'/**': 'JOINED_FILTERS,-restTokenValidationFilter,-restExceptionTranslationFilter'
]
grails {
plugin {
springsecurity {
rest {
login.useJsonCredentials = true
login.usernamePropertyName = "keyword"
token {
rendering.usernamePropertyName = "keyword"
rendering.authoritiesPropertyName = "roles"
rendering.tokenPropertyName = "access_token"
validation.useBearerToken = true
validation.enableAnonymousAccess = true
}
}
}
}
}
答案 0 :(得分:1)
事实证明,在服务器实例上没有显示的域类的问题与功能测试中的服务器实例在单独的jvm(分叉的jvm模式)上运行这一事实有关,所以所有调用都需要通过遥控器发送。
我最终使用了远程控制插件,如下所示(回想一下我在Grails 2.4.4上),如BuildConfig.groovy
所示:
plugins {
...
compile ":rest-client-builder:2.0.4-SNAPSHOT"
compile ":remote-control:1.5"
...
}
我有几个问题,将请求发送到更新到最新版本后解析的正确URL,如上所示。另外,不要忘记将springsecurity核心设置配置为allowAll用于grails-remote-control网址。