django 如何更改TokenObtainPairView的错误响应消息?

unguejic  于 2023-05-01  发布在  Go
关注(0)|答案(2)|浏览(184)

TokenObtainPairView类用于使用jwt令牌的基于令牌的认证。
现在,当我为用户输入错误的登录信息时,我会收到一条错误消息:

{
   "detail" : "No active account found with the given credentials"
}

我想把它改成:

{
   "detail" : "email or password is incorrect!"
}
f45qwnt8

f45qwnt81#

# app/views.py

from django.utils.translation import ugettext_lazy as _
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.views import TokenObtainPairView

class MyTokenObtainPairSerializer(TokenObtainPairSerializer):

    default_error_messages = {
        'no_active_account': _('email or password is incorrect!')
    }

class MyTokenObtainPairView(TokenObtainPairView):
    serializer_class = MyTokenObtainPairSerializer

然后,使用MyTokenObtainPairView,其中使用TokenObtainPairView,e。例如:

# app/urls.py

from app.views import MyTokenObtainPairView

urlpatterns = [
  ...
  path('auth/token/', MyTokenObtainPairView.as_view())
  ...
]
kknvjkwl

kknvjkwl2#

创建自定义Login视图,该视图接受用户名和密码,并根据给定的凭据进行身份验证,然后返回访问权限,并在用户通过身份验证时刷新令牌

from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth import authenticate

def get_tokens_for_user(user):
   refresh = RefreshToken.for_user(user)

   return {
     'refresh': str(refresh),
     'access': str(refresh.access_token),
   }

class LoginView(APIView):
   def post(self,request):
       username= request.data["username"]
       password = request.data["password"]

       user = authenticate(username=username,password=password)
       if user:
           return Response(get_tokens_for_user(user))
       return Response({"error":"email or password isincorrect!"},status=status.HTTP_203_NON_AUTHORITATIVE_INFORMATION)

相关问题