jwt spring security 따라가기

bluesky·2021년 10월 30일
0
post-thumbnail

[1] jwt 설명

{1} 정의

json web token의 줄임말.
json 객체를 사용해서 토큰 자체에 정보를 저장하는 web token.

{2} 장단점.

왜 쓸까?
장점 : 세션쿠키 방식과 달리 별도의 저장소 관리가 필요 없다.

단점 : JWT는 한 번 발급되면 유효기간이 완료될 때 까지는 계속 사용이 가능합
(해결책 : 기존의 Access Token의 유효기간을 짧게 하고 Refresh Token이라는 새로운 토큰을 발급합)

{3} 구성.

header payload signature 3개의 부분으로 구성되어 있음.

header : 타입(JWT)과 알고리즘(BASE64 같은)을 담는다.
payload : 보통 유저정보(id같은)와 만료기간이 객체형으로 담긴다.
signature : header, payload를 인코딩 한 값을 합친뒤 SECRET_KEY로 해쉬한다.

[2] spring security 소개.

  • 참고용 spring mvc
  • spring mvc request lifecycle

  • spring security architecture.

{2} 개념 설명

  • securitycontext holder
    보안 주체의 세부 정보를 포함하여 응용프래그램의 현재 보안 컨텍스트에 대한 세부 정보가 저장된다.

  • [ SecurityContext ]
    Authentication을 보관하는 역할을 하며, SecurityContext를 통해 Authentication 객체를 꺼내올 수 있다.

  • [ Authentication ]
    Authentication는 현재 접근하는 주체의 정보와 권한을 담는 인터페이스이다. Authentication 객체는 Security Context에 저장되며, SecurityContextHolder를 통해 SecurityContext에 접근하고, SecurityContext를 통해 Authentication에 접근할 수 있다.

{3} 인증 과정.

2 인증전 토큰 생성
3 토큰 정보 authentication manager에 전달.

  • authentication manager : 인증을 처리하는 부분. 인증 성공시, 성공한 객체를 security context에 저장.
    인증 실패시, authenticationexception을 발생.

4 authentication provider 호출.
실제 인증을 처리. 인증전 객체를 받아, 인증이 완료된 객체를 반환한다.

5 UserDetailService 호출.
: loadUserByUsername을 이용해 저장소에 있는 유저 정보를 추출.

6번인 UserDetails를 반환 받음.
UserDetails? : 유저의 상세정보를 가진 클래스. getter setter와 계정 활성화 여부 상태 메서드를 가짐.

7-9 : 반환과정.
10 : 성공적이면 security context holder에 그 정보를 저장.

[3] 전략

  • AuthenticationEntryPoint : 인증과정에서 실패하거나 인증헤더(Authorization)를 보내지 않게되는 경우, 실패를 처리하는 로직.

  • JwtFilter : 토큰의 유효성을 확인하고 인증정보를 저장함.(나중에 로그인 정보를 받기 위함)

  • UsernamePasswordAuthenticationFilter : 안씀.

[4] 시연.

[5] 참고자료

https://mangkyu.tistory.com/76

profile
SMART https://github.com/dongseoki?tab=repositories

0개의 댓글