Skip to content

9주차 과제 [루크]#22

Open
yujining3827 wants to merge 68 commits into
mainfrom
luke/week9
Open

9주차 과제 [루크]#22
yujining3827 wants to merge 68 commits into
mainfrom
luke/week9

Conversation

@yujining3827
Copy link
Copy Markdown
Collaborator

🚩 관련 이슈


📌 구현 결과

❶ JWT 기반 인증/인가 기능 구현

  • Spring Security 기반 JWT 인증 방식 적용
  • Stateless 환경 설정 및 JWT 필터(Security FilterChain) 등록
  • JwtAuthFilter를 통해 Authorization 헤더의 AccessToken 검증 로직 구현

JwtAuthFilter 상세 코드

@RequiredArgsConstructor
public class JwtAuthFilter extends OncePerRequestFilter {

   private final JwtUtil jwtUtil;
   private final CustomUserDetailsService customUserDetailsService;

   @Override
   protected void doFilterInternal(
           @NonNull HttpServletRequest request,
           @NonNull HttpServletResponse response,
           @NonNull FilterChain filterChain
   ) throws ServletException, IOException {

       try {
           // 토큰 가져오기
           String token = request.getHeader("Authorization");

           System.out.println("URI = " + request.getRequestURI());
           System.out.println("TOKEN = " + token);

           // token이 없거나 Bearer가 아니면 넘기기
           if (token == null || !token.startsWith("Bearer ")) {

               System.out.println("NO TOKEN");

               filterChain.doFilter(request, response);
               return;
           }

           // Bearer이면 추출
           token = token.replace("Bearer ", "");

           // AccessToken 검증하기: 올바른 토큰이면
           if (jwtUtil.isValid(token)) {

               // 토큰에서 이메일 추출
               String email = jwtUtil.getEmail(token);

               // 인증 객체 생성: 이메일로 찾아온 뒤, 인증 객체 생성
               UserDetails user = customUserDetailsService.loadUserByUsername(email);
               Authentication auth = new UsernamePasswordAuthenticationToken(
                       user,
                       null,
                       user.getAuthorities()
               );
               // 인증 완료 후 SecurityContextHolder에 넣기
               SecurityContextHolder.getContext().setAuthentication(auth);
           }
           filterChain.doFilter(request, response);
       } catch (Exception e) {

           e.printStackTrace();

           ObjectMapper mapper = new ObjectMapper();
           BaseErrorCode code = GeneralErrorCode.UNAUTHORIZED;

           response.setContentType("application/json;charset=UTF-8");
           response.setStatus(code.getStatus().value());

           ApiResponse<Void> errorResponse = ApiResponse.onFailure(code,null);

           mapper.writeValue(response.getOutputStream(), errorResponse);
       }
   }
}

❷ 회원가입 기능 개선

[기존 코드에서 수정]

  • 신규 회원 기본 권한(Role.USER) 저장 로직 추가
  • 음식 카테고리 선호 정보 저장 기능 연동

[추가 기능]

  • 회원가입 성공 시 AccessToken 발급 기능 구현
    image

❸ 로그인 기능 구현

  • 로그인 성공 시 JWT AccessToken 발급으로 로직 수정
  • JWT claim(email, role) 정보 포함 처리
image image

❹ 사용자 인증 정보 기반 API 개선

  • 마이페이지 조회 API를 JWT 인증 기반 구조로 변경
  • @AuthenticationPrincipal을 사용하여 인증 사용자 정보 조회
image

❓ 리뷰 요청


🤔 질문


💬 기타 공유 사항




@yujining3827 yujining3827 changed the title Luke/week9 9주차 과제 [루크] May 28, 2026
Copy link
Copy Markdown
Member

@yangjiae12 yangjiae12 left a comment

Choose a reason for hiding this comment

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

수고하셨습니다~

Comment on lines +44 to +50
public String getEmail(String token) {
try {
return getClaims(token).getPayload().getSubject(); // Parsing해서 Subject 가져오기
} catch (JwtException e) {
return null;
}
}
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

JWT 파싱 실패 시 null을 반환하기보다 예외를 그대로 위임하는 것이 더 안전할 것 같습니다! null 반환은 호출부에서 예상치 못한 NPE를 유발할 수 있어, 현재처럼 필터에서 예외를 처리하는 구조라면 getEmail()은 값을 반환하는 책임만 갖도록 분리하는 것도 좋을 것 같습니다~

Comment on lines +46 to +47
// Bearer이면 추출
token = token.replace("Bearer ", "");
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

이미 Bearer 로 시작하는지 검증한 상태라면 replace()보다 substring(7)이 의도를 조금 더 명확하게 표현할 수 있을 것 같습니다~

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