我正在体验我认为可能是一个错误。委托人返回为UsernamePasswordAuthenticationToken
我正在使用Spring Boot和Spring Security。通常情况下,一切都运行良好,但当我通过HttpServletRequest
或直接从控制器获得委托人时,出于某种奇怪的原因将其转换为UsernamePasswordAuthenticationToken
。当我使用SecurityContextHolder.getContext().getAuthentication().getPrincipal()
时,它返回正确的对象。
请参阅下面的代码,请参阅最后6行左右的注释以了解实际返回的内容。
@RequestMapping(method = RequestMethod.POST)
public ElementDto postElement(@RequestBody @Valid ElementDto element, BindingResult bindingResult, HttpServletRequest httpServletRequest, Principal principal) {
logger.info("postElement - {}", element);
if (bindingResult.hasErrors()) {
throw new SpringBootCommonError(bindingResult.getAllErrors().get(0).getDefaultMessage(), SpringBootCommonErrorEnum.VALIDATION);
}
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = (UsernamePasswordAuthenticationToken)principal; /*is of type UsernamePasswordAuthenticationToken*/
Principal requestPrincipal = httpServletRequest.getUserPrincipal();/*is of type UsernamePasswordAuthenticationToken*/
Principal principalFromCast = (Principal)usernamePasswordAuthenticationToken.getPrincipal();/*is of type User (what I want)*/
Object securityPrincipal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();/*is of type (what I want)*/
element.setUploadedBy(((User) httpServletRequest.getUserPrincipal()).getEntityNo());
return elementService.createElement(element);
}
我明白UsernamePasswordAuthenticationToken我的问题是,为什么是我的校长被返回UsernamePasswordAuthenticationToken例如下面的代码工作 '((用户)((UsernamePasswordAuthenticationToken)本金).getPrincipal())。getEntityNo()'但是这个代码不不是'((用户)主体).getEntityNo()' 我不认为我应该把它转换成UsernamePasswordAuthenticationToken,然后返回到本金,如果它最初是主体 –
它不是很清楚,你指的是什么'委托人'在你的评论。这取决于身份验证提供程序如何实现它。 HttpServeletRequest和SecurityContext都会返回你正确的主体,即UsernamePasswordAuthenticationToken – Simon