【问题标题】:Spring integration test - AuthenticationPrincipal not injectedSpring集成测试-未注入AuthenticationPrincipal
【发布时间】:2016-10-04 11:17:35
【问题描述】:

我正在尝试在我的项目中使用 kotlin,它是为 angularjs 前端提供服务的 REST API 端点。我使用 spring rest doc 作为我们的 api 文档。

在迁移时,我发现我的安全上下文没有注入到测试用例中。

使用 mockito-kotlin 测试类(主要由 Intellij 转换):

@RunWith(SpringJUnit4ClassRunner::class)
@ContextConfiguration(classes = arrayOf(MockAppConfig::class))
@WebAppConfiguration
class UserLoginDocumentation {

@get:Rule
var restDocumentation = JUnitRestDocumentation("target/generated-snippets")

private var mockMvc: MockMvc? = null

@Autowired
private val context: WebApplicationContext? = null

@Before
fun setUp() {
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context!!)
            .apply<DefaultMockMvcBuilder>(documentationConfiguration(this.restDocumentation)
            .uris().withScheme("https").withHost("myhost.com").withPort(443)).build()
    val authentication = TestingAuthenticationToken(MyUserDetailsService.MyUserDetails(1L), null)
    SecurityContextHolder.getContext().authentication = authentication
}

@Autowired
lateinit var userLoginService: UserLoginService

@Test
@Throws(Exception::class)
fun loginTest() {

    whenever(userLoginService!!.getUserInfo(any(), any(), any())).thenReturn(LoginUserInfo())
    this.mockMvc!!.perform(post("/myloginURL/user")//the remaining is not important....

控制器:

@RequestMapping("/myloginURL")
@RestController
class UserLoginController
@Autowired constructor(
    val userLoginService: UserLoginService) {

@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = "/user", method = arrayOf(RequestMethod.POST), produces = arrayOf(MediaType.APPLICATION_JSON_VALUE))
fun getUser(@AuthenticationPrincipal userDetail: MyUserDetails, 
    request: HttpServletRequest, @RequestParam lang: String): LoginUserInfo? {
    return userLoginService.getUserInfo(userDetail.userId, request.getHeader("Authorization"), lang)
}

}

这里userDetail 不为空,但userDetail.userId 为空。所以看起来测试类中的身份验证没有注入到控制器调用中。

我是不是做错了什么,或者如何解决?

【问题讨论】:

  • 我的错,这不是 kotlin 特定的问题。 Java 的行为相同。但是在 kotlin 中,我使 getUserInfo 的第一个参数不可为空,有没有办法通过 Spring 正确注入 userDetail?

标签: kotlin spring-test spring-test-mvc


【解决方案1】:

我应该使用MockMvcBuilders.webAppContextSetup(this.context!!) .apply(springSecurity(springSecurityFilterChain))

springSecurityFilterChain@EnableWebSecurity 自动连接

之后我可以使用 csrf 和我想要的用户,userDetail 被注入到控制器中。

参考:http://docs.spring.io/spring-security/site/docs/current/reference/html/test-mockmvc.html#test-mockmvc-setup

【讨论】:

  • 非常感谢,你用那句话拯救了我的一天:springSecurityFilterChain 与 @EnableWebSecurity 自动连接
猜你喜欢
  • 1970-01-01
  • 2012-10-17
  • 2021-06-26
  • 2016-11-14
  • 1970-01-01
  • 2017-08-04
  • 2022-01-19
  • 1970-01-01
  • 2012-02-17
相关资源
最近更新 更多