Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store JWT Token in DB with Django REST Framework

We use JWT Token with Django REST Framework. Where store JWT Token and I want to store JWT Token in my DB. Because I used this API for mobile app.

Here create JWT Token

class LoginView(APIView):
     permission_classes = [permissions.AllowAny]

    def post(self, request, format=None):
        """
        Return a Valid token if username and password
        is valid for a given client
        """
        try:
            username = request.data['username']
            password = request.data['password']
            user = authenticate(username=user.username, password=password)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
                    jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

                    payload = jwt_payload_handler(user)
                    token = jwt_encode_handler(payload)

                    ind = Individual.objects.filter(user_id=user.id).first()
                    ind.login_flag = True
                    ind.save()

here, I used JWT Token Verification

class LogoutView(APIView):
    permission_classes = (IsAuthenticated, )
    authentication_classes = (JSONWebTokenAuthentication, )

    def post(self, request, format=None):
        .......
        .......

Its working proper with JWT Token verification on postman. But I want to where store token and How to store JWT Token in my DB.

like image 970
Rajendra Badgujar Avatar asked Nov 19 '25 16:11

Rajendra Badgujar


1 Answers

As others on this thread already suggested, the major point is not storing JWT in your database. It is meant for stateless authentication. You should be able to generate and retrieve the tokens using a secret.

One way to accomplish this in Django is using the SECRET_KEY to encode and decode the data in JWT like:

import jwt

from django.conf import settings
from django.contrib.auth import get_user_model
from your_project import custom_exceptions as exc


def get_token_for_user(user, scope):
    """
    Generate a new signed token containing
    a specified user limited for a scope (identified as a string).
    """
    data = {
        "user_%s_id" % (scope): str(user.id),
    }
    return jwt.encode(data, settings.SECRET_KEY).decode()


def get_user_for_token(token, scope):
    """
    Given a selfcontained token and a scope try to parse and
    unsign it.

    If max_age is specified it checks token expiration.

    If token passes a validation, returns
    a user instance corresponding with user_id stored
    in the incoming token.
    """
    try:
        data = jwt.decode(token, settings.SECRET_KEY)
    except jwt.DecodeError:
        raise exc.NotAuthenticated("Invalid token")

    model_cls = get_user_model()

    try:
        user = model_cls.objects.get(pk=data["user_%s_id" % (scope)])
    except (model_cls.DoesNotExist, KeyError):
        raise exc.NotAuthenticated("Invalid token")
    else:
        return user

The function get_token_for_user would bind the user_id and scope of the token together and encode it using the secret key. One might be able to only decode it if the SECRET_KEY is known.

get_token_for_user & get_user_for_token are the utility function you can use once you get the Token from your HTTP_AUTHORIZATION header to verify if the token is successfully decoded and valid.

These utility function also support a scope for each token you create. So, for example, you can say that this particular token is just for authentication and mention the scope as authentication.

The scope parameter accepted by these utility function is just a string, so you can use whatever scope you can think of, and while decoding it for a particular API call, you know what scope the token should be available in.

You can modify these as you desire to support JWT for authentication.

like image 51
Sanyam Khurana Avatar answered Nov 21 '25 08:11

Sanyam Khurana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!