[์ผ] token ๊ธฐ๋ฐ ์ธ์ฆ ๋ก์ง (Interceptor์์ ์ ํจ์ฑ ํ์ธ)
๊ฐ ์ปจํธ๋กค๋ฌ์์ 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();
}
}

๊ฐ๊ฐ์ ์ฐ๋ ๋ ๋ณ๋ก ๋ณ๋์ ์ ์ฅ๊ณต๊ฐ์ ์ ๊ณตํ๋ ์ปจํ ์ด๋
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