Skip to content

Conversation

@Shinsu98
Copy link
Collaborator

@Shinsu98 Shinsu98 commented Oct 23, 2025

요구사항

기본

JWT 컴포넌트 구현

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

리팩토링 - 로그인

  • 미션 9와 마찬가지로 Spring Security의 formLogin + 미션 9의 인증 흐름은 그대로 유지하면서 필요한 부분만 대체합니다.

  • 세션 생성 정책을 STATELESS로 변경하고, sessionConcurrency 설정을 삭제하세요.

    http
        .sessionManagement(session -> session
            ...
            .sessionCreationPolicy(...)
        )
    
  • AuthenticationSuccessHandler 컴포넌트를 대체하세요.

    • 기존 구현체는 LoginSuccessHandler입니다.

    • JwtLoginSuccessHandler를 정의하고 대체하세요.

      @Component
      public class LoginSuccessHandler implements AuthenticationSuccessHandler {
          ...
          @Override
        public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
            Authentication authentication) throws IOException, ServletException {
            ...
        }
      }
      
      • 인증 성공 시 JwtProvider를 활용해 토큰을 발급하세요.

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

    • 설정에 추가하세요.

    http
        .formLogin(login -> login
            ...
            .successHandler(jwtLoginSuccessHandler)
        )
    

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

주요 변경사항

스크린샷

image

멘토에게

  • 여러가지로 찾아보면서 코드를 작성하였지만 아직 토큰에 대한 이해도가 부족해 현재 코드에서 오류가 나고 있습니다. 토큰에 대한 복습을 완료한 후 오류에 대한 리팩토링을 이어나가도록 하겠습니다.

@Value("${jwt.refresh-token-expiration-days:7}")
private int refreshTokenExpirationDays;

public String generateAccessToken(Map<String, Object> claims, String subject) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

토큰 발급시 이와 같이 claim 정보나 subject정보를 파라미터로 가져오는 방식은 위험합니다.
UserDetail 정보를 파라미터로 받고 안에서 풀어내는 방식을 쓰시는게 좋을것 같아요!

try {
JWSSigner signer = new MACSigner(secretKey.getBytes(StandardCharsets.UTF_8));

Date expiration = new Date(System.currentTimeMillis() + accessTokenExpirationMinutes * 60 * 1000);
Copy link
Collaborator

Choose a reason for hiding this comment

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

60 * 1000 정보 자체도 환경변수에서 계산하도록 관리하는게 좋습니다.

response.setContentType(MediaType.APPLICATION_JSON_VALUE);

if (authentication.getPrincipal() instanceof DiscodeitUserDetails userDetails) {
response.setStatus(HttpServletResponse.SC_OK);
Copy link
Collaborator

Choose a reason for hiding this comment

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

여기를 try catch로 묶고 예외 처리를해서 500에러에 해당하는 에러를 발생시켜주면 더 좋을것 같아요!

String header = request.getHeader("Authorization");

// 요청 헤더(Authorization)에 Bearer 토큰이 포함된 경우에만 인증 시도
if (header != null && header.startsWith("Bearer ")) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

이런것도 내부 메서드로 구현하면 코드가 깔끔해질 것 같아요!


try {
// JwtProvider를 통해 엑세스 토큰의 유효성을 검사(서명 검증 및 클레임 파싱)
Map<String, Object> claims = jwtTokenProvider.getClaims(token);
Copy link
Collaborator

Choose a reason for hiding this comment

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

검증로직을 JwtProvider로 가져가면 책임분리가 깔끔하게 될것 같습니다.

SecurityContextHolder.getContext().setAuthentication(authentication);
}
} catch (Exception ignored) {
// 유효하지 않으면 인증 없이 다음 필터로 진행
Copy link
Collaborator

Choose a reason for hiding this comment

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

여기 로깅이라도 남겨두는게 좋지 않을까 생각이 듭니다.

@Override
public JwtDto refreshAccessToken(String refreshToken) {
try {
Map<String, Object> claims = jwtTokenProvider.getClaims(refreshToken); // 서명/만료 검증 포함(실패 시 예외)
Copy link
Collaborator

Choose a reason for hiding this comment

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

검증 로직을 jwtTokenProvider로 가져가도록 해보시면 좋을것 같습니다.

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.

4 participants