My server is using Django Rest Framework. My mobile app logs in using token authentication. However, I also have a webview in the mobile app where I need to log in. I can't inject the auth token on every request in the webview, so I use the auth token for authenticating this endpoint and then create a session from it. This is the code:

class CreateSessionView(APIView):
    authentication_classes = [TokenAuthentication]
    permission_classes = (permissions.AllowAny,)
    throttle_classes = [ScopedRateThrottle]
    throttle_scope = 'auth_token_verify'
    renderer_classes = [TemplateHTMLRenderer]

    def get(self, request, format=None):
        return Response({}, template_name='pages/create-session.html')
        # this template has a <form> that includes a {% csrf_token %} and authtoken

    def post(self, request, format=None):
            user = Token.objects.get(key=request.POST['authtoken']).user
            login(request, user, backend='django.contrib.auth.backends.ModelBackend')
            raise AuthenticationFailed() 
        return redirect(reverse('home'))

My question is: Is there a vulnerability here? If so, how can I secure it?

  • 1
    When dealing with sessions, you must always use CSRF protection.
    – bhorkarg
    Mar 26 '20 at 9:12
  • @bhorkarg I did some research and you're right. Mar 26 '20 at 9:30
  • Need to explain your question more (I deleted my answer for now). How would the sequence of calls go? Is it that you would first GET (the csrf token and the authtoken) from your app and then load the data into the WebView? And then the user would POST a form in the WebView to login?
    – bhorkarg
    Mar 30 '20 at 10:06
  • @bhorkarg I have an endpoint that has a form with an embedded CSRF token. The web view loads that endpoint (GET), and the some JS on the page autosubmits (POST) with the CSRF and auth tokens. Mar 31 '20 at 17:45
  • How do you get the auth token to the form in the first place for the JS to autosubmit? Wouldn't this be some sort of a chicken-or-egg problem? - to get auth token you need to be logged in but to log in you need the auth token. If I understand correctly, you'd be giving out the auth token in the GET request without any authentication.
    – bhorkarg
    Apr 1 '20 at 6:36

See the answer here, it may help: Session Authentication vs Token Authentication

From what I understand from the answer, there is nothing wrong with using a token to authenticate, and then generating a session from the aforementioned token.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.