How can I return user ID with token in Django?

后端 未结 4 944
广开言路
广开言路 2020-12-21 00:34

I generate tokens using default view in Django:

url(r\'^login/\', rest_auth_views.obtain_auth_token),

I have a problem because my front-end

4条回答
  •  被撕碎了的回忆
    2020-12-21 01:27

    You could override rest_framework.authtoken.views.ObtainAuthToken.post in order to get the result you want.

    myapp/views.py

    from rest_framework.authtoken.views import ObtainAuthToken
    from rest_framework.authtoken.models import Token
    from rest_framework.response import Response
    
    
    class CustomObtainAuthToken(ObtainAuthToken):
        def post(self, request, *args, **kwargs):
            response = super(CustomObtainAuthToken, self).post(request, *args, **kwargs)
            token = Token.objects.get(key=response.data['token'])
            return Response({'token': token.key, 'id': token.user_id})
    

    myapp/urls.py

    from django.conf.urls import url
    
    from .views import CustomObtainAuthToken
    
    urlpatterns = [
        url(r'^authenticate/', CustomObtainAuthToken.as_view()),
    ]
    

    Sample results

    $ http :8000/authenticate/ username=someuser password=secretpassword
    HTTP/1.0 200 OK
    Allow: POST, OPTIONS
    Content-Language: en
    Content-Type: application/json
    Date: Tue, 22 Mar 2017 18:30:10 GMT
    Server: WSGIServer/0.2 CPython/3.5.1
    Vary: Accept-Language, Cookie
    X-Frame-Options: SAMEORIGIN
    
    {
        "id": 16, 
        "token": "82e0bc9980a6b2c9a70969b0f8dc974418dda399"
    }
    

    The idea here is to override the post method of the ObtainAuthToken view class. Here all I have done is call the parent class to get the token, then look up that token to find the associated user id.

    Hope that helps.

提交回复
热议问题