Django令牌授权 - 通过重写ObtainAuthToken类来自定义obtain_jwt_token

时间:2017-02-16 09:38:11

标签: django-rest-auth

我的目标是覆盖obtain_jwt_token以便更好地控制程序的返回值,并且在Cordova site中我发现了一个关于如何执行此操作的奇怪且粗略的信息:< / p>

  

请注意,默认的obtain_auth_token视图显式使用JSON   请求和响应,而不是使用默认渲染器和解析器   您的设置中的类。如果您需要定制版本的   gets_auth_token视图,你可以通过覆盖它来实现   ObtainAuthToken视图类,并在您的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()

可能性很大,我的代码看起来很傻,而我只是迷失了想要谷歌。我在Djagno没什么经验,所以请帮帮我!

2 个答案:

答案 0 :(得分:0)

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

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)

您可以通过自定义Django的auth模型将您的默认设置更改为仅通过电子邮件进行检查,但我很高兴有两种选择。

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

答案 1 :(得分:0)

  1. 在views.py中,文件添加以下代码并根据需要进行自定义。
def jwt_response_payload_handler(token, user=None, request=None):
    return {
        'token': token,
        'user': UserSerializer(user, context={'request': request}).data
    }

默认值为{'token':令牌}

  1. 也在您的settings.py文件中添加
JWT_AUTH = {
    
    'JWT_RESPONSE_PAYLOAD_HANDLER':
        'api.user.views.jwt_response_payload_handler',
 }

('api.user.views.jwt_response_payload_handler', )是您的自定义jwt_response_payload_handler的路径

要获取更多帮助,您可以查看here