reg: DRF login API

167 views
Skip to first unread message

Amitesh Sahay

unread,
Apr 8, 2021, 8:48:27 AM4/8/21
to Django Users
HI,

I have created a simple login API through django rest framework. Below is the code snippet:

from django.contrib.auth import login
from rest_framework.generics import ListCreateAPIView
from rest_framework import status
from rest_framework.response import Response
from rest_framework.authtoken.serializers import AuthTokenSerializer
from rest_framework.permissions import IsAuthenticated, IsAdminUser, AllowAny
from knox.views import LoginView as KLView
from knox.models import AuthToken
from .serializers import RegistrationSerializers
from .models import NewEmployeeProfile

class loginAPIView(KLView):
permission_classes = [AllowAny]

def post(self, request, format=None):
serializer = AuthTokenSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
login(request, user)
return super(loginAPIView, self).post(request, format=None)
 
URLS.py
from django.urls import path
from knox import views as knox_views
from .views import UserRegisterView, loginAPIView


urlpatterns = [
    path('register/', UserRegisterView.as_view(), name='register'),
    path('login/', loginAPIView.as_view(), name='login'),
    ]


Now when I do a POST request in postman with the email and the password. It throws error:

{
    "detail": "Invalid token."
}

Note:: Since I am using knox to generate token. So, when I do a new registration I get token as well. See sample below:

{
    "status": "OK",
    "message": {
        "email": "test...@test.com",
        "first_name": "est",
        "last_name": "Sah",
        "employee_code": "6124368",
        "contact": "7500078619",
        "dob": null
    },
    "token": "db058f23ecc70f4fa3de4ac69a04dc48bb7579a63aea1ad3d038ce59b1511890"

I tried both, password and token to authenticate, but I am getting the same error. In the cmd prompt where the dev server is running, I am seeing below message

========================
[08/Apr/2021 15:26:33] "POST /apii/login/ HTTP/1.1" 403 27
Forbidden: /apii/login/
========================
In the postman raw body, I am inserting below json data

{
    "email": "test...@test.com",
    "password": "db058f23ecc70f4fa3de4ac69a04dc48bb7579a63aea1ad3d038ce59b1511890"
}


Below is the settings.py content for DRF

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        #'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'knox.auth.TokenAuthentication',
    ],
}



httpie output

python.exe -m httpie 127.0.0.1:8000/apii/login/ 'Authorization: Token db058f23ecc70f4fa3de4ac69a04dc48bb7579a63aea1ad3d038ce59b1511890'

HTTP/1.1 405 Method Not Allowed
Allow: POST, OPTIONS
Content-Length: 40
Content-Type: application/json
Date: Thu, 08 Apr 2021 11:52:31 GMT
Referrer-Policy: same-origin
Server: WSGIServer/0.2 CPython/3.6.8
Vary: Accept, Cookie
X-Content-Type-Options: nosniff
X-Frame-Options: DENY

{
    "detail": "Method \"GET\" not allowed."
}


urlpatterns = [ path('register/', UserRegisterView.as_view(), name='register'), path('login/', loginAPIView.as_view(), name='login'), ]
Not sure if I am doing it the right way, please suggest. Thank you....

RANGA BHARATH JINKA

unread,
Apr 8, 2021, 9:15:19 AM4/8/21
to django...@googlegroups.com
Hi, You have to specify the POST method in the command
http -a USERNAME POST https://api.github.com/repos/httpie/httpie/issues/83/comments body='HTTPie is awesome! :heart:' 
All the best

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/2028966691.640551.1617886057684%40mail.yahoo.com.


--
Thanks and Regards

J. Ranga Bharath
cell: 9110334114

RANGA BHARATH JINKA

unread,
Apr 8, 2021, 9:16:19 AM4/8/21
to django...@googlegroups.com
Refer the docs

Amitesh Sahay

unread,
Apr 8, 2021, 9:56:21 AM4/8/21
to django...@googlegroups.com
Hey Ranga,

Below is the new output

python.exe -m httpie -a xxx....@xxxx.com POST 127.0.0.1:8000/apii/login/ 'Authorization: Token db058f23ecc70f4fa3de4ac69a04dc48bb7579a63aea1ad3d038ce59b1511890'

http: password for xxx....@xxxx.com@127.0.0.1:8000: "this asked for the password, so I entered and hit return key. Below is the output"

HTTP/1.1 400 Bad Request
Allow: POST, OPTIONS
Content-Length: 79
Content-Type: application/json
Date: Thu, 08 Apr 2021 13:49:29 GMT
Referrer-Policy: same-origin
Server: WSGIServer/0.2 CPython/3.6.8
Vary: Accept, Cookie
X-Content-Type-Options: nosniff
X-Frame-Options: DENY

{
    "password": [
        "This field is required."
    ],
    "username": [
        "This field is required."
    ]
}

The above output is little surprising and interesting. I am using custom User model, where email is used in place of username and happens to be the unique constraint. SO I really do not understand the above output. If you need more data, do let me know.

Regards,
Amitesh 

RANGA BHARATH JINKA

unread,
Apr 8, 2021, 10:24:43 AM4/8/21
to django...@googlegroups.com
Hi,

Try providing a username and password. Check if it is working or not

Amitesh Sahay

unread,
Apr 8, 2021, 11:37:23 AM4/8/21
to django...@googlegroups.com
HI, 

-a xxx....@xxxx.com --> username

After I entered 

python.exe -m httpie -a xxx....@xxxx.com POST 127.0.0.1:8000/apii/login/ 'Authorization: Token db058f23ecc70f4fa3de4ac69a04dc48bb7579a63aea1ad3d038ce59b1511890'

It prompted for the password, I entered, that is when I got the output

Regards,
Amitesh 


Reply all
Reply to author
Forward
0 new messages