์ƒ์„ธ ์ปจํ…์ธ 

๋ณธ๋ฌธ ์ œ๋ชฉ

[์€ผ] token ๊ธฐ๋ฐ˜ ์ธ์ฆ ๋กœ์ง (Interceptor์—์„œ ์œ ํšจ์„ฑ ํ™•์ธ)

๋ณธ๋ฌธ

728x90

๊ธฐ์กด ๋ฐฉ์‹๊ณผ ๋ฌธ์ œ์  

๊ฐ ์ปจํŠธ๋กค๋Ÿฌ์—์„œ 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

๊ด€๋ จ๊ธ€ ๋”๋ณด๊ธฐ