Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a login API using Django Rest Framework?

I want to create a login api (or use an existing one if it is already pre-bundled) using django rest framework. However, I'm completely at a loss. Whenever I send a post request to the django rest framework "login" url, it just sends back the browsable api template page...

MY CONFIGURATION

urls.py

url(r'^api/v1/', include('rest_framework.urls', namespace='rest_framework')) 

settings.py

REST_FRAMEWORK = {     'DEFAULT_AUTHENTICATION_CLASSES': (         'rest_framework.authentication.BasicAuthentication',         'rest_framework.authentication.SessionAuthentication',     ) } 

WHAT I WANT

Request:

POST /api/v1/login  username='name' pass='pass' 

Response:

200 OK "{username: 'name', 'userId': '54321'}" set-cookie: sessionid="blahblah" 
like image 532
JayPrime2012 Avatar asked Jan 23 '14 19:01

JayPrime2012


People also ask

Can we create REST API using Django?

Creating a REST API in Django The Django application is all set - the settings are defined, our application is prepared, the model is in place and we've created an administrator user to verify that the model is registered to the admin dashboard. Now, let's implement the CRUD functionality for our model.

Which authentication is best for web API Django?

JSON Web Token Authentication A package for JWT authentication is djangorestframework-simplejwt which provides some features as well as a pluggable token blacklist app.


1 Answers

Take a look at the api view from django-rest-framework-jwt. It's an implementation for creating auth tokens rather than cookie sessions, but your implementation will be similar. See views.py and serializers.py. You can probably use the serializers.py unchanged, and just adjust your views to return the right parameters and possibly set the session cookie (can't recall if that's already performed in authentication).

like image 90
Kevin Stone Avatar answered Sep 19 '22 13:09

Kevin Stone