스프링 시큐리티는 SecurityContext에 인증된 Authentication 객체를 넣어두고 현재 스레드 내에서 공유되도록 관리된다.
토큰 인증 이후 편의적으로 현재 인증된 유저를 가져오기 위해 @AuthenticationPrincipal 어노테이션을 통해 UserDetails 인터페이스를 구현한 유저 객체를 주입할 때 사용한다.
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends GenericFilterBean {
private final JwtProvider jwtProvider;
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
String token = jwtProvider.resolveToken((HttpServletRequest) request);
try {
if (token != null && jwtProvider.validateJwtToken(request, token)) {
Authentication authentication = jwtProvider.getAuthentication(token);
// SecurityContext 에 Authentication 객체를 저장합니다.***
SecurityContextHolder.getContext().setAuthentication(authentication);
}
} catch (Exception e) {
e.printStackTrace();
}
chain.doFilter(request, response);
}
}
JWT 같은 토큰을 활용하면 요청된 요청마다의 토큰 정보를 읽어 매번 인증을 진행할 것이다. 따라서 매 요청마다 Filter를 활용하여 SecurityContext에 요청마다 인증되는 Authentication 객체를 set 시킬 것이고 이후에 Controller 에서 @AuthenticationPrincipal을 활용하여 가져올 수 있다.
@PostMapping("/update_like")
public String updateLike(@RequestParam String postId, @RequestParam String action, @AuthenticationPrincipal UserDetailsImpl userDetails) {
User info = userDetails.getUser();
likeService.updateLike(Long.parseLong(postId), action, info);
return "redirect:/post/" + postId;
}
홍서님
보고싶어써여~!!!!!!!!!!!!!(뒷북)