Django serve image authorization with JWT

Viewed 145

I am trying to serve images from my Django Rest framework server. I need these images to be secured with my user's JWT token.

ie. If user GETs profile 1, and profile 1 has image ABC. Unless the user has access to Profile 1, they should not be able to navigate to BASE_URL/static/images/ABC.jpg and get an image.

How to I implement a valid token check?

1 Answers

You cannot secure static.

If your user is authenticated, you have access to authenticated user at your http-method -> request.user.

If the images aren´t huge, you can store them as base64 in your database.

If you would like to check your token manually without using django´s authentication system, you can try this

from rest_framework_simplejwt.authentication import JWTTokenUserAuthentication
from rest_framework_simplejwt.tokens import AccessToken
from rest_framework.exceptions import AuthenticationFailed, NotAuthenticated

class Test(APIView):
    def get(self, request):
        token = request.COOKIES.get('JWT', None)  # the cookie should be set prior to that point
        if token is None:
            return NotAuthenticated()
        else:
            payload= JWTTokenUserAuthentication().get_user(AccessToken(token, verify=True).payload)
            user = User.objects.filter(id=payload.get('user_id')).first()
            if user:
                # your code
            else:
                # raise unknown user
        return ...

I didn´t test the code but I partly used it.

Related