gpt4 book ai didi

grails - Grails SpringSecurity Spock功能测试UserDetailsS​​ervice:在以下位置找不到用户

转载 作者:行者123 更新时间:2023-12-02 14:42:18 30 4
gpt4 key购买 nike

我正在使用带有功能性Spock 0.7的Spring Security Core 2.0-RC4,Spring Security REST 1.5.0.M1的Grails 2.4.4。

我正在使用功能测试来测试要构建的REST API的 Controller 。设置测试时,我先创建一个User,一个管理员Role,然后创建一个UserRole。当我检查User是否已使用spock功能测试的相应凭据持久保存时,我发现一切正常。

但是,在进行身份验证时,调用GormUserDetailsServiceUser.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实例刷新到数据库中。我已经尝试使用此方法的 UserRole块内的 User调用printin所有的 findAll()withTransaction,但它们仍然不返回任何内容。

有人有什么想法吗?我应该 mock 我不是的东西吗?我在功能测试中使用了 @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中的spring安全设置:
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
}
}
}
}
}

最佳答案

事实证明,域类未出现在服务器实例上的问题与以下事实有关:功能测试中的服务器实例在单独的jvm上运行(派生的jvm模式),因此所有调用都必须通过远程。

我最终使用了BuildConfig.groovy中所示的远程控制插件,如下所示(记得我在Grails 2.4.4上):

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

如上所示,将请求发送到正确的URL后遇到了一些问题,这些请求在更新到最新版本后已解决。另外,不要忘记将您的springsecurity核心设置配置为grails-remote-control url的allowAll。

关于grails - Grails SpringSecurity Spock功能测试UserDetailsS​​ervice:在以下位置找不到用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28567742/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com