我测试我的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""""))
}
}