상세 컨텐츠

본문 제목

[쀼] token 기반 인증 로직 (Interceptor에서 유효성 확인)

🔥Activites/[프로젝트] 진행하며 생각을 했다

by :부셔져버린개발자 2025. 1. 4. 19:21

본문

기존 방식과 문제점 

각 컨트롤러에서 Authorizaiton 헤더를 검증하여
token이 있는지 확인하고 userId를 가져오는 로직이 중복됨을 발견할 수 있었다.
 
그리고 만약 인증 방식이 변경된다면 모든 Controller를 수정해야 한다 
그리고 잘못된 토큰을 가진 요청은 컨트롤러에 도달하기 전에 차단하기 위한 방안을 고려하고자 했다 
 

 
 
 


개선 방안 

Interceptor에 아래 로직 담자
 
1. JWT 토큰 유효성 검사
- 토큰 파싱 & 서명 검증 & 만료 검사 
 
2. 토큰에서 추출한 userId로 사용자 유효한지 확인
 
3. Auth Context에 사용자 정보 저장
유효한 사용자라면 Auth Context에 사용자 정보 저장
 

public class AuthContext {
	private static ThreadLocal<Long> userIdThreadLocal = new ThreadLocal<>();

	public static Long getUserId() {
		return userIdThreadLocal.get();
	}

	public static void setUserId(Long userId) {
		userIdThreadLocal.set(userId);
	}

	public static void clear() {
		userIdThreadLocal.remove();
	}
}

 

각 Controller에서 사용 방식

ThreadLocal 이란?

각각의 쓰레드 별로 별도의 저장공간을 제공하는 컨테이너

import java.util.concurrent.atomic.AtomicInteger; 

 public class ThreadId { 
     // 다음에 할당할 스레드 ID를 포함하는 원자 정수 
     private static final AtomicInteger nextId = new AtomicInteger(0); 

     // 각 스레드의 ID를 포함하는 스레드 로컬 변수 
     private static final ThreadLocal<Integer> threadId = 
         new ThreadLocal<Integer>() { 
             @Override protected Integer initialValue() { 
                 return nextId.getAndIncrement(); 
         } 
     }; 

     // 필요한 경우 현재 스레드의 고유 ID를 할당하여 반환합니다 
     public static int get() { 
         return threadId.get(); 
     } 
 }

 
 
https://docs.oracle.com/javase/8/docs/api/java/lang/ThreadLocal.html

ThreadLocal (Java Platform SE 8 )

Returns the current thread's "initial value" for this thread-local variable. This method will be invoked the first time a thread accesses the variable with the get() method, unless the thread previously invoked the set(T) method, in which case the initialV

docs.oracle.com

 

728x90

관련글 더보기