gpt4 book ai didi

带发布的Spring WebMvcTest返回403

转载 作者:行者123 更新时间:2023-12-01 15:04:02 24 4
gpt4 key购买 nike

我想知道代码的问题在哪里,每次运行后期测试(无论目标对象是哪种 Controller 或方法)时,我都会返回403错误,在某些情况下我希望返回401,而在其他情况下则返回401 200个响应(带有身份验证)。

这是我的 Controller 的代码段:

@RestController
@CrossOrigin("*")
@RequestMapping("/user")
class UserController @Autowired constructor(val userRepository: UserRepository) {
@PostMapping("/create")
fun addUser(@RequestBody user: User): ResponseEntity<User> {
return ResponseEntity.ok(userRepository.save(user))
}
}

而我针对该 Controller 的单元测试
@RunWith(SpringRunner::class)
@WebMvcTest(UserController::class)
class UserControllerTests {
@Autowired
val mvc: MockMvc? = null

@MockBean
val repository: UserRepository? = null

val userCollection = mutableListOf<BioRiskUser>()

@Test
fun testAddUserNoAuth() {
val user = BioRiskUser(
0L,
"user",
"password",
mutableListOf(Role(
0L,
"administrator"
)))
repository!!
`when`(repository.save(user)).thenReturn(createUser(user))
mvc!!
mvc.perform(post("/create"))
.andExpect(status().isUnauthorized)
}

private fun createUser(user: BioRiskUser): BioRiskUser? {
user.id=userCollection.count().toLong()
userCollection.add(user)
return user
}
}

我想念什么?

根据要求,我的安全配置...
@Configuration
@EnableWebSecurity
class SecurityConfig(private val userRepository: UserRepository, private val userDetailsService: UserDetailsService) : WebSecurityConfigurerAdapter() {
@Bean
override fun authenticationManagerBean(): AuthenticationManager {
return super.authenticationManagerBean()
}

override fun configure(auth: AuthenticationManagerBuilder) {
auth.authenticationProvider(authProvider())
}

override fun configure(http: HttpSecurity) {
http
.csrf().disable()
.cors()
.and()
.httpBasic()
.realmName("App Realm")
.and()
.authorizeRequests()
.antMatchers("/img/*", "/error", "/favicon.ico", "/doc")
.anonymous()
.anyRequest().authenticated()
.and()
.logout()
.invalidateHttpSession(true)
.clearAuthentication(true)
.logoutSuccessUrl("/user")
.permitAll()
}

@Bean
fun authProvider(): DaoAuthenticationProvider {
val authProvider = CustomAuthProvider(userRepository)
authProvider.setUserDetailsService(userDetailsService)
authProvider.setPasswordEncoder(encoder())
return authProvider
}
}

和身份验证提供者
class CustomAuthProvider constructor(val userRepository: UserRepository) : DaoAuthenticationProvider() {
override fun authenticate(authentication: Authentication?): Authentication {
authentication!!
val user = userRepository.findByUsername(authentication.name)
if (!user.isPresent) {
throw BadCredentialsException("Invalid username or password")
}
val result = super.authenticate(authentication)
return UsernamePasswordAuthenticationToken(user, result.credentials, result.authorities)
}


override fun supports(authentication: Class<*>?): Boolean {
return authentication?.equals(UsernamePasswordAuthenticationToken::class.java) ?: false
}
}

最佳答案

您需要在@ContextConfiguration(classes=SecurityConfig.class)批注之后在自己的UserControllerTests类的顶部添加@WebMvcTest(UserController::class)

关于带发布的Spring WebMvcTest返回403,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52994063/

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