본문 바로가기
TIL

[TIL] python으로 jwt 구현하기

by 다람이도토리 2022. 2. 15.

python을 활용하여 jwt를 구현하기.

python에는 jwt 모듈이 존재하여, jwt를 쉽게 구현할 수 있다.

jwt의 기본 구조를 다시 보면,

header + payload + signature

3가지로 구성되어 있다. 구현할 때는 payload에 집중하여 구현하게 된다.

import jwt
import datetime

SECRET_PRE = "<personal_choose>"

def create_token(token, email):
    
    encoded = jwt.encode(
        payload = {'exp':datetime.dattime.utcnow() + datetime.timeelta(seconds = 300),
                   'email': email},
        key = SECRET_PRE + token, 
        algorithm = 'HS256')
    return encoded

encoded를 할 때는 paylaod와 key, 알고리즘을 넘긴다.  즉 key+알고리즘 부분이 header가 될 것이다.

주의사항은 payload를 만들때, exp 즉, 만료 시점을 꼭 넣어 주어야 하는 것에다.!

 

jwt를 검증하는 방법도 간단하다.

def validate_token(get_token, token):
    try:
        jwt.decode(get_token, SECRET_PRE + token, algorithms = 'HS256')
    except jwt.ExpiredSignatureError:
        return status.HTTP_401_UNAUTHORIZED
    except jwt.InvalidTokenError:
        return status.HTTP_401_UNAUTOHRIZED
    else:
        return True

만료 여부에 따른 error를 뱉어주게 된다.

'TIL' 카테고리의 다른 글

[TIL] curl 읽기  (0) 2022.03.17
[TIL] 0313_ Python으로 request get/post하기  (0) 2022.03.13
[TIL] 토큰 기반 인증, JWT 개념  (0) 2022.02.15
[TIL] 220119 O 면접 후기  (0) 2022.01.19
[TIL] 220118 면접 오답노트 정리  (0) 2022.01.18