1

我在 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 功能测试中使用适当的凭据持久保存时,我发现一切正常。

但是,在进行身份验证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()调用没有找到任何东西,即使我已经在我的功能测试中确认我已经将 User 实例刷新到数据库中。我已经尝试在此方法的块内调用printin 所有的UserRoles 和Users ,但它们仍然没有返回任何内容。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
                }
            }
        }
    }
}
4

1 回答 1

1

事实证明,域类未显示在服务器实例上的问题与功能测试中的服务器实例在单独的 jvm(分叉 jvm 模式)上运行这一事实有关,因此所有调用都需要通过偏僻的。

我最终使用了如下远程控制插件(回想一下我在 Grails 2.4.4 上),如下所示BuildConfig.groovy

plugins {
    ...
    compile ":rest-client-builder:2.0.4-SNAPSHOT"
    compile ":remote-control:1.5"
    ...
}

我在向正确的 url 发送请求时遇到了几个问题,这些问题在更新到上面看到的最新版本后得到了解决。另外,不要忘记为 grails-remote-control url 配置您的 springsecurity 核心设置为 permitAll。

于 2015-03-09T23:37:24.027 回答