Django 令牌授权 - 通过覆盖获取验证令牌类自定义获取_jwt_token

Cra*_*rog 4 django-rest-auth

我的目标是覆盖obtain_jwt_token以更好地控制程序的返回值,在文档中我只发现了一个关于如何执行此操作的奇怪而粗略的信息:

请注意,默认的 acquire_auth_token 视图明确使用 JSON 请求和响应,而不是在您的设置中使用默认的渲染器和解析器类。如果您需要一个自定义版本的获取_auth_token 视图,您可以通过覆盖获取验证令牌视图类来实现,并在您的 url conf 中使用它

至于现在,我的尝试是这样的:

urlpatterns = [
   url(r'^api-token-auth/', my_customized_view),
]

class Foo(ObtainAuthToken):
    def post(self):
       # here goes my customized code

my_customized_view = Foo.as_view()
Run Code Online (Sandbox Code Playgroud)

赔率是我的代码看起来很愚蠢,而我只是失去了尝试谷歌它。我在 Djagno 方面的经验很少,所以请帮我解决这个问题!

小智 5

我刚刚经历了同样的理解之旅,因为我希望返回用户并允许电子邮件或用户名登录。文档并不完全清楚,但如 auth 令牌所述,您可以对 JWT 执行相同的操作。obtain_auth_token 即为获取授权令牌,如获取_jwt_token 为获取JSONWebToken。这是我覆盖的登录方法:

from rest_framework_jwt.settings import api_settings
from rest_framework_jwt.views import ObtainJSONWebToken

jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
jwt_decode_handler = api_settings.JWT_DECODE_HANDLER


class LoginView(ObtainJSONWebToken):
    def post(self, request, *args, **kwargs):
        # by default attempts username / passsword combination
        response = super(LoginView, self).post(request, *args, **kwargs)
        # token = response.data['token']  # don't use this to prevent errors
        # below will return null, but not an error, if not found :)
        res = response.data
        token = res.get('token')

        # token ok, get user
        if token:
            user = jwt_decode_handler(token)  # aleady json - don't serialize
        else:  # if none, try auth by email
            req = request.data  # try and find email in request
            email = req.get('email')
            password = req.get('password')
            username = req.get('username')

            if email is None or password is None:
                return Response({'success': False, 
                                'message': 'Missing or incorrect credentials',
                                'data': req},
                                status=status.HTTP_400_BAD_REQUEST)

            # email exists in request, try to find user
            try:
                user = User.objects.get(email=email)
            except:
                return Response({'success': False, 
                                'message': 'User not found',
                                'data': req},
                                status=status.HTTP_404_NOT_FOUND)

            if not user.check_password(password):
                return Response({'success': False, 
                                'message': 'Incorrect password',
                                'data': req},
                                status=status.HTTP_403_FORBIDDEN)

            # make token from user found by email
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            user = UserSerializer(user).data

        return Response({'success': True,
                        'message': 'Successfully logged in',
                        'token': token,
                        'user': user}, 
                        status=status.HTTP_200_OK)
Run Code Online (Sandbox Code Playgroud)

您可以通过自定义 Django 的身份验证模型将默认设置更改为仅通过电子邮件检查,但我很高兴同时拥有这两个选项。

我开始创建一个 api 样板。有一个 requirements.txt 文件和一个 config.example.py 文件,供任何想要下拉查看其余内容的人使用。 https://github.com/garyburgmann/django-api-boilerplate