티스토리 뷰

Spring

Spring Security - 아키텍쳐 TheadLocal

엔꾸꾸 2019. 9. 13. 23:21

Spring Security - ArcheTecher_ThreadLocal

  • java.lang 패키지에서 제공하는 Thread Scope Variable
  • 쓰레드 수준의 데이터 저장소이다.
  • SecurityContextHolder의 기본 전략이다.

같은 쓰레드 내에서만 공유
따라서 같은 쓰레드라면 해당 데이터를 메서드 매개변수로 사용하지않아도 데이터를 전달할 수 있다.

Context 생성

  • ThreadLocal을 사용해서 한 쓰레드내에서 Account객체를 공유 할 수 있는 Context를 구현한다.
  • Account 객체를 ThreadLocal에 저장하고, 가져오는 로직만 존재하는 매우 간단한 클래스이다.

Context 활용

  • SampleService의 dashboard() 메서드 수정하기

dashboard() 메서드를 호출하면 AccountContext에 저장된 account 객체를 꺼내와 username을 출력하는 매우 간단한 메서드이다.

  • SampleController 의 dashboard api를 수정해서 dashboard() 메서드를 활용하기

수정된 SampleController는 다음과 같다. dashboard API를 자세히 살펴보자

수정된 dashboard API

  • /dashboard로 요청을 보내면 accountRepository에서 account를 새롭게 조회한다.
  • 조회한 Account객체를 AccountContext에 저장한다.
  • sampleService의 dashboard() 메서드를 호출한다.

테스트 진행

GET localhost:8080/account/USER/user/1234

- 유저권한을 가지는 user/1234 를 생성하도록 요청한다.

 

GET localhost:8080/dashboard 로 요청을 보내면 인증을 위한 시큐리티 로그인 페이지가 나타나고, 생성한 유저로 인증을 시도한다.

 

인증에 성공하면 다음과 같이 dashboard page가 나타나며 console에는 username = user 라는 로그가 남게된다.

- SampleService의 dashboard() 메서드에서 구현한 AccountContext를 활용한 정보 출력이 되는것이다.

 

 

정리

ThreadLocal을 활용하여 직접 AccountContext를 구현해 보았다.

스프링 시큐리티에서는 SecurityContextHolder가 SecurityContext를 활용하여 Authentication 객체를 알아서 저장해주기 때문에 SecurityContextHolder를 이용해 Authentication 객체에 접근이 가능한 것이다.

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함