我是Django的新手,我想实施JWT身份验证,以便仅查看当前登录用户的API数据。有人可以给我提示如何在Django(2.1版)中构造JWT的实现吗?
w910488011 回答:注册用户登录后如何在Web App中实现JWT认证?
您已经提到您同时使用django-rest-framework
和django-rest-framework-simplejwt
。我建议创建一个单独的APIView
来获取当前登录用户的详细信息。您还应该为User
模型创建一个序列化器。
如果您在设置中正确添加了以下声明,那么当前已通过身份验证的用户应该在request.user
中可用。
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',),}
这种情况足以满足您的情况:
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
class UserDetailsAPIView(APIView):
permission_classes = [IsAuthenticated]
def get(self,request,*args,**kwargs):
user = request.user
profile = request.user.profile
data = {
'username': request.user.username,'email': request.user.email,'salary': profile.salary,'company': profile.company,'address': profile.address,'gender': profile.gender,}
return Response(data)