带发布的Spring WebMvcTest返回403

标签 spring rest spring-boot kotlin

我想知道代码的问题在哪里,每次运行后期测试(无论目标对象是哪种 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/

相关文章:

java - 找不到媒体类型 Jersey MessageBodyWriter = text/plain

java - 处理 Spring Web 中的 # 字符

java - 为什么我的 Spring @Autowired 字段为空?

java - 如何合并 springframework.beans.factory.UnsatisfiedDependencyException 堆栈跟踪?

django - 'Product' 类型的对象不是 JSON 可序列化的

java - 如何以 ISO 格式返回 Date 对象而不是 Java 中的时间戳?

java - Spring - 在凭据错误的情况下返回非公开响应

json - 在 RESTful Web 服务中,响应 DTO 是否应该包含它们的子 DTO?

java - Spring Boot、Gradle 和非 Maven 依赖项

spring-boot - Spring boot application.properties 重用值