서버쪽 sign_in() 함수에서 sha256 해시함수를 이용해 암호화한다.
pw_hash = hashlib.sha256(password_receive.encode('utf-8')).hexdigest()
서버쪽 sign_in() 함수에서 payload를 기입하고, 토큰을 생성한다.
payload = {
'id': username_receive,
'exp': datetime.utcnow() + timedelta(seconds=60 * 60 * 24 * 7),
}
token = jwt.encode(payload, SECRET_KEY, algorithm='HS256').decode('utf-8')
프론트에서 로그인을 할때 쿠키에 토큰을 저장해준다.
success: function (response) {
if (response['result'] == 'success') {
$.cookie('mytoken', response['token'], {path: '/'});
window.location.replace("/")
} else {
alert(response['msg'])
}
}
로그인 이후 서버쪽 함수에서는 해당 유저의 토큰을 이용해 유저 정보를 가져다가 쓸 수 있다.
def user(username):
token_receive = request.cookies.get('mytoken')
payload = jwt.decode(token_receive, SECRET_KEY, algorithms=['HS256'])