Implement JWT On Django Rest

Pada tutorial sebelumnya kita sudah mempelajari tentang

selanjutnya kali ini kita akan mengimplementasikan JWT pada Django Rest Framework

install jwt pada django :
pip install djangorestframework-jwt
tambahkan pada setting.py script di bawah ini untuk membuat screet key dan token expired
SECRET_KEY = "12345"
EXPIRY_TIME = datetime.timedelta(seconds=20)
JWT_AUTH = {
    'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=20),  # Token expires * seconds after being issued
    'JWT_ALLOW_REFRESH': True,
    'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(seconds=120),  # Token can be refreshed up to * seconds after being issued
 }

 

buat function untuk encode dan decode JWT
def get_token(request):
    username =request.GET.get('username')
    password = request.GET.get('password')
    if username and password is not None:
        payload = {
            'username': username,
            'password':password,
            'exp':datetime.utcnow() + settings.EXPIRY_TIME
        }
        token = jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256')
        token =str(token).replace("b'","")
        token = str(token).replace("'", "")
        token= {'token':token}
        return HttpResponse(
            json.dumps(token)
        )
    else:
        return HttpResponse(
            json.dumps({'Error': "Invalid credentials"}),
            status=400
        )
def get_verivy_token(request):
    token =request.GET.get('token')
    try:
        payload = jwt.decode(token, settings.SECRET_KEY, algorithm='HS256')
        return HttpResponse(
            json.dumps(payload),
            status=200
        )
 
    except jwt.ExpiredSignature:
        return HttpResponse(json.dumps({'Error': "Token is invalid"}))
    except:
        return HttpResponse(json.dumps({'Error': "Token DoesNotExist"}))
good luck ….!
mm

Alfin F

Technopreneur , Developer, Advisor

More Posts

Follow Me:
TwitterLinkedIn