I want to do a rest api to be able to login to my Django app (from an Android app) using a request like
curl -X POST -d "username=myusername&password=mypassword" http://localhost:12345/rest/api-auth/login/
which should return a session id that I can use in future requests. It seems that I should use the SessionAuthentication authentication scheme, but there is no doc about it.
I'm aware of this question, but I'd like not to use any other app.
Any suggestion/pointer?
Token authentication is appropriate for client-server setups, such as native desktop and mobile clients. Make sure to run manage.py migrate after changing your settings. The rest_framework. authtoken app provides Django database migrations.
1) The name of the CSRF header to be sent to Django is 'X_CSRFToken'. 2) The token is stored in the browser as 'csrftoken'. 3) We should by default send our credentials with requests, such as our CSRF token and, once authenticated, the Session cookie.
The /api-auth/login/
resource is only for authentication in the browseble api.
To use session authentication, you must create a session first.
You must have a login resource, which accepts user credentials and authenticates a user, using the Django authentication system.
On requesting that resource the client will get a cookie header.
The cookie and csrf token must be used in future requests.
curl -v -X POST https://example.com/api/user/login/ -d 'username=user&password=pass'
...
> Set-Cookie: csrftoken=TqIuhp8oEP9VY32tUDcfQyUwn3cqpYCa; expires=Fri, 15-May-2015 12:48:57 GMT; Max-Age=31449600; Path=/
> Set-Cookie: sessionid=4yb4s456lbvd974oijbdha7k3l6g52q3; expires=Fri, 30-May-2014 12:48:57 GMT; Max-Age=1209600; Path=/
DRF supports basic authentication too. You can use it to authenticate user initially and create session. Here is an example:
from django.contrib.auth import login
from rest_framework.authentication import BasicAuthentication, SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
class MyBasicAuthentication(BasicAuthentication):
def authenticate(self, request):
user, _ = super(MyBasicAuthentication, self).authenticate(request)
login(request, user)
return user, _
class ExampleView(APIView):
authentication_classes = (SessionAuthentication, MyBasicAuthentication)
permission_classes = (IsAuthenticated,)
def get(self, request, format=None):
content = {
'user': unicode(request.user),
'auth': unicode(request.auth), # None
}
return Response(content)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With