Django使用JWT提供图像授权



我正在尝试从我的Django Rest框架服务器提供图像。我需要使用用户的JWT令牌来保护这些图像。

ie。如果用户获取配置文件1,并且配置文件1具有映像ABC。除非用户能够访问配置文件1,否则他们不应该能够导航到BASE_URL/static/images/ABC.jpg并获取图像。

如何实现有效的令牌检查?

您无法保护static

如果你的用户是经过身份验证的,你可以通过http-method ->request.user.

如果图片不是很大,你可以将它们以base64格式存储在数据库中。

如果你想在不使用django的认证系统的情况下手动检查你的令牌,你可以试试这个

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 ...

我没有测试代码,但我部分使用了它。

最新更新