https://github.com/OPGG-HACKTHON/MusicWard-Server/issues/105
특정 유저는 자신이 등록한 데이터만 수정 및 삭제가 가능하도록 제한해야 한다.
JwtTokenFilfer
를 지날 때 token
값이 유효하면 SecurityContext
에 Authentication
객체를 저장한다.
@Component
@RequiredArgsConstructor
public class JwtTokenFilter extends OncePerRequestFilter {
private final JwtTokenProvider jwtTokenProvider;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String token = jwtTokenProvider.resolveToken(request);
if (token != null && jwtTokenProvider.validateToken(token)) {
Authentication authentication = jwtTokenProvider.authentication(token);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
filterChain.doFilter(request, response);
}
}
jwtTokenProvider.authentication()
과 token의 subject를 활용하여 조회를 진행한다.
public Authentication authentication(String token) {
UserDetails userDetails = authDetailsService.loadUserByUsername(getTokenSubject(token));
return new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities());
}
music-ward에서는 UserDetails를 상속받은 User 엔티티 객체를 활용한다.
SecurityUtil
에 static 메소드를 활용하여 SecurityContext
의 Authentication
정보를 조회한다. 아래 getCurrentUserId
메소드를 활용하면 현재 요청한 유저의 토큰 정보를 활용하여 저장한 Authentication 객체에서 해당 유저에 대한 정보를 조회할 수 있다.
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class SecurityUtil {
public static Long getCurrentUserId() {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null
|| authentication.getPrincipal() == null
|| !(authentication.getPrincipal() instanceof UserDetails)) {
throw new CredentialsNotFoundException();
}
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
User user = (User) userDetails;
return user.getId();
}
}