私はバグかもしれないと思います。プリンシパルが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)校長).getPrincipal())。getEntityNo()'動作しますが、このコードはありませんUsernamePasswordAuthenticationTokenを理解します'((User)プリンシパル).getEntityNo() ' 私はそれをUsernamePasswordAuthenticationTokenにキャストして元のプリンシパルだった場合は元に戻す必要があるとは思わない –
それはあまり明確ではないあなたのコメントに。それは、認証プロバイダーがそれをどのように実装するかによって異なります。 HttpServeletRequestとSecurityContextの両方がUsernamePasswordAuthenticationTokenである正しいプリンシパルを返します。 – Simon