2

I am using Django-Rest-Framework with token authentication. In my Android App I want to open a webview and display some content from a view which needs authentication.

Because of this I wrote a rest call to fetch a session id.

/rest/getsessionid/ => looks like that:

from django.contrib.sessions.backends.db import SessionStore

class GetSessionKeyView(APIView):

    def get(self, request, format=None):
        if request.user.is_authenticated:
            s = SessionStore()
            s.create()
            return Response({'sessionid': s.session_key})
        return Response({'notauthenicated': True})

Unfortunately the returned sessionid is not working. Why?

Philipp S.
  • 827
  • 17
  • 41

1 Answers1

0

I finally found a way.

class GetSessionKeyView(APIView):

    def get(self, request, format=None):
        if request.user.is_authenticated:
            if 'HTTP_COOKIE' not in request.META or request.META['HTTP_COOKIE'] == '':
                login(request, request.user, backend='django.contrib.auth.backends.ModelBackend')
                return Response({
                    'sessionid': request.session.session_key
                })
            else:
                return Response({'ERROR': 'Cookies not allowed'})
        return Response({'notauthenicated': True})

You have to login again first to create a session.

EDIT: Don't forget to block cookies to protect this from CSRF attacks.

Philipp S.
  • 827
  • 17
  • 41