Skip to content

Conversation

@kosy00
Copy link
Collaborator

@kosy00 kosy00 commented Oct 23, 2025

요구사항

기본

JWT 컴포넌트 구현

  • JWT 의존성을 추가하세요.
implementation 'com.nimbusds:nimbus-jose-jwt:10.3'
  • 토큰을 발급, 갱신, 유효성 검사를 담당하는 컴포넌트(JwtTokenProvider)를 구현하세요.

리팩토링 - 로그인

  • 세션 생성 정책을 STATELESS로 변경하고, sessionConcurrency 설정을 삭제하세요.
http
    .sessionManagement(session -> session
        ...
        .sessionCreationPolicy(...)
    )
  • AuthenticationSuccessHandler 컴포넌트를 대체하세요.

  • 인증 성공 시 JwtProvider를 활용해 토큰을 발급하세요.

    • 엑세스 토큰은 응답 Body에 포함하세요.
    • 리프레시 토큰은 쿠키(REFRESH_TOKEN)에 저장하세요.
  • 200 JwtDto로 응답합니다.

JWT 인증 필터 구현

  • 엑세스 토큰을 통해 인증하는 필터(JwtAuthenticationFilter)를 구현하세요.
public class JwtAuthenticationFilter extends OncePerRequestFilter {

  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
      FilterChain filterChain) throws ServletException, IOException {...}
  • 요청 당 한번만 실행되도록 OncePerRequestFilter를 상속하세요.

  • 요청 헤더(Authorization)에 Bearer 토큰이 포함된 경우에만 인증을 시도하세요.

  • JwtProvider를 통해 엑세스 토큰의 유효성을 검사하세요.

  • 유효한 토큰인 경우 UsernamePasswordAuthenticationToken 객체를 활용해 인증 완료 처리하세요.

UsernamePasswordAuthenticationToken authentication =
            new UsernamePasswordAuthenticationToken(
                userDetails,
                null,
                userDetails.getAuthorities()
            );
SecurityContextHolder.getContext().setAuthentication(authentication);

리프레시 토큰을 활용한 엑세스 토큰 재발급

  • 리프레시 토큰을 활용해 엑세스 토큰을 재발급하는 API를 구현하세요.

    • API 스펙
      • 엔드포인트: POST /api/auth/refresh
      • 요청: Header Cookie: REFRESH_TOKEN=…
      • 응답
      • 리프레시 토큰이 유효한 경우: 200 JwtDto
      • 리프레시 토큰이 유효하지 않은 경우: 401 ErrorResponse
      • permitAll 설정에 포함하세요.
      • 이 API는 엑세스 토큰이 없거나 만료된 상태에서 호출하게 됩니다.
  • 리프레시 토큰 Rotation을 통해 보안을 강화하세요.

  • 토큰 재발급 API로 대체할 수 있는 컴포넌트를 모두 삭제하세요.

    • Me API (GET /auth/me)
  • RememberMe

    • 쿠키에 저장된 리프레시 토큰이 RememberMe의 기능을 대체할 수 있습니다.

리팩토링 - 로그아웃

  • 쿠키에 저장된 리프레시 토큰을 삭제하는 LogoutHandler를 구현하세요.
public class JwtLogoutHandler implements LogoutHandler {

  @Override
  public void logout(HttpServletRequest request, HttpServletResponse response,
      Authentication authentication) {...}
  • 구현한 핸들러를 추가하세요.
http
  .logout(logout -> logout
      ...
      .addLogoutHandler(jwtLogoutHandler)
  )

심화

  • 심화 항목 1
  • 심화 항목 2

주요 변경사항

스크린샷

멘토에게

  • 셀프 코드 리뷰를 통해 질문 이어가겠습니다.

@joonfluence
Copy link
Collaborator

p1. 이번에도 현재 sprint10 내용 외에도 여러 이전 작업 내역들이 혼재되어 있습니다.
이번 작업만 보일 수 있도록 sprint8 내역만 남겨주세요.
이건 꼭 고쳐주세요!

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

JwtTokenProvider가 토큰 발급, 갱신, 유효성 검사 기능을 모두 포함하여 정확하게 구현되었습니다.

)
.logout(logout -> logout
.logoutUrl("/api/auth/logout")
.addLogoutHandler(jwtLogoutHandler)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LogoutHandler이 제대로 등록 됐습니다

)
.formLogin(login -> login
.loginProcessingUrl("/api/auth/login")
.successHandler(jwtLoginSuccessHandler)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LoginSuccessHandler이 제대로 등록 됐습니다

Comment on lines +28 to +53
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
response.setContentType(MediaType.APPLICATION_JSON_VALUE);

if (authentication.getPrincipal() instanceof DiscodeitUserDetails userDetails) {
UserDto userDto = userDetails.getUserDto();
Map<String, Object> claims = Map.of("roles", userDetails.getAuthorities());
String subject = userDto.email();

String accessToken = jwtTokenProvider.generateAccessToken(claims, subject);
String refreshToken = jwtTokenProvider.generateRefreshToken(claims, subject);

Cookie refreshTokenCookie = new Cookie("REFRESH_TOKEN", refreshToken);
refreshTokenCookie.setHttpOnly(true);
refreshTokenCookie.setPath("/");
refreshTokenCookie.setMaxAge(7*24*60*60);
response.addCookie(refreshTokenCookie);

JwtDto jwtDto = new JwtDto(userDto, accessToken, refreshToken);

response.setStatus(HttpServletResponse.SC_OK);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding("UTF-8");
response.getWriter().write(objectMapper.writeValueAsString(jwtDto));

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

응답 쿠키에 리프레시 토큰, 응답 Body에 엑세스 토큰을 잘 저장합니다.

Comment on lines +42 to +53
private Map<String, Object> verifyJws(HttpServletRequest request) {
String authorization = request.getHeader("Authorization");
if (authorization == null || !authorization.startsWith("Bearer ")) {
throw new RuntimeException("JWT 토큰이 존재하지 않습니다.");
}
String jws = authorization.replace("Bearer ","");
boolean isValid = jwtTokenProvider.validateToken(jws);
if (!isValid) {
throw new RuntimeException("유효하지 않은 JWT 토큰입니다.");
}
return jwtTokenProvider.getClaims(jws);
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bearer 식별 처리 정상

Comment on lines +59 to +69
JwtDto jwtDto = authService.reissueToken(refreshToken);

String newRefreshToken = jwtDto.getRefreshToken();
Cookie cookie = new Cookie("REFRESH_TOKEN", newRefreshToken);
cookie.setHttpOnly(true);
cookie.setSecure(true);
cookie.setPath("/");
cookie.setMaxAge(7 * 24 * 60 * 60); // 7 days
response.addCookie(cookie);
return ResponseEntity.ok(jwtDto);
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Service 계층으로 빼는게 더 좋을 것 같습니다

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants