webmcv测试和安全性可以与get一起使用,但不能与put一起使用

时间:2019-10-11 13:26:53

标签: java spring spring-boot spring-mvc spring-security

我测试我的get映射没有任何问题,但是对put映射的类似测试返回403。为什么?我应该如何配置才能使所有测试通过?

我的应用程序:

@SpringBootApplication
class DemoApplication

@RestController
class MyController {

    @GetMapping("/api/a")
    fun a(principal: Principal): String = """"hello ${principal.name}""""

    @PutMapping("/api/b")
    fun b(principal: Principal): String = """"hello ${principal.name}""""
}


@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
class SecurityConfig : WebSecurityConfigurerAdapter() {

    @Bean
    override fun authenticationManagerBean(): AuthenticationManager {
        return super.authenticationManagerBean()
    }

    override fun configure(auth: AuthenticationManagerBuilder){
        auth.inMemoryAuthentication()
                .withUser("admin")
                .password("admin")
                .roles("USER")
    }

    override fun configure(web: WebSecurity) {}

    override fun configure(http: HttpSecurity) {}

    @Bean
    fun passwordEncoder(): PasswordEncoder = NoOpPasswordEncoder.getInstance()
}        

fun main(args: Array<String>) {
    runApplication<DemoApplication>(*args)
}

我的测试:

@WebMvcTest(MyController::class)
class MockedTokenTest {

    @Autowired
    lateinit var mockMvc: MockMvc

    @Test
    fun `call get api using mocked token`() {

        mockMvc.perform(
                get("/api/a")
                        .with(authentication(TestingAuthenticationToken(UserPrincipal("admin3"), 2)))
        )
                .andExpect(status().isOk)
                .andExpect(content().json(""""hello admin3""""))
    }

    @Test
    fun `call put api using mocked token`() {

        mockMvc.perform(
                put("/api/b")
                        .with(authentication(TestingAuthenticationToken(UserPrincipal("admin3"), 2)))
        )
                .andExpect(status().isOk)
                .andExpect(content().json(""""hello admin3""""))
    }

}

0 个答案:

没有答案
相关问题