Describe the bug
A request cannot obtain a SecurityContextusing @PathVariable, but using @RequestParam can obtain a SecurityContext.
// Unable to obtain SecurityContext when using @PathVariable
// The "request" is FirewalledRequest[ org.springframework.session.web.http.SessionRepositoryFilter$SessionRepositoryRequestWrapper@7f85823c].
@GetMapping("/key/{accountId}")
public Result<KeyPairDTO> generateKeyPair(@NotBlank @PathVariable String accountId, HttpServletRequest request) {
KeyPairDTO keyPairDTO = userAccountService.getKeyPairDTO(accountId);
return ResultUtils.success(keyPairDTO);
}
// But able to obtain SecurityContext when using @RequestParam
// The "request" is SecurityContextHolderAwareRequestWrapper[ org.springframework.security.web.header.HeaderWriterFilter$HeaderWriterRequest@107f4341]
@GetMapping("/key")
public Result<KeyPairDTO> generateKeyPair(@NotBlank @RequestParam String accountId, HttpServletRequest request) {
KeyPairDTO keyPairDTO = userAccountService.getKeyPairDTO(accountId);
return ResultUtils.success(keyPairDTO);
}
To Reproduce Write a similar controller method and simulate it for testing. (My Spring Boot version is 3.0.3.)
Expected behavior Able to obtain SecurityContext when using @PathVariable
Sample This controller method is simple and common, so I will not provide an example. Please search for similar testing programs yourself. If your test results differ from mine, or if you need more program context information, please feel free to discuss. Thank you very much!
Comment From: insight720
I changed the request path from /key/{accountId} to/{accountId}/key, and this problem no longer exists. 😓
@GetMapping("/{accountId}/key")
public Result<KeyPairDTO> generateKeyPair(@NotBlank @PathVariable String accountId) {
KeyPairDTO keyPairDTO = userAccountService.getKeyPairDTO(accountId);
return ResultUtils.success(keyPairDTO);
}
Comment From: sjohnr
Thanks for getting in touch @insight720, but it feels like this is a question that would be better suited to Stack Overflow. We prefer to use GitHub issues only for bugs and enhancements. Feel free to update this issue with a link to the re-posted question (so that other people can find it) or add a minimal sample that reproduces this issue if you feel this is a genuine bug.
Having said that, I am not seeing you access the SecurityContext. I am unable to reproduce the issue but may not be understanding what you're trying to do. If you would like us to look at this issue, please provide a minimal sample.