'Custom Django Rest Framework authentication validating when 'None' is returned
I am working on implementing JWT for authentication. Of course, this means I have to do some custom authentication. According to the docs, "If authentication is not attempted, return None." So, I have code that checks for an authorization header (where the JWT resides) and returning "None" if an authorization header does not exist. This means that authorization was not attempted (and according to the docs) I should return None. However, Django is saying that the user is authorized:
Root/authentication/TokenAuthentication/TokenAuthentication
from rest_framework import status
from django.http import HttpResponse
from rest_framework.authentication import get_authorization_header, BaseAuthentication
from django.contrib.auth.models import User
import jwt, json
class TokenAuthentication(BaseAuthentication):
def authenticate(self, request):
auth = get_authorization_header(request).split()
if not auth:
return None
Login.py
@api_view(['POST'])
def login_view(request):
if not request.data:
return Response({'Error': "Please provide username/password"}, status="400")
username = request.data['username']
password = request.data['password']
try:
user = User.objects.get(username=username)
if not user.check_password(password):
raise User.DoesNotExist
except User.DoesNotExist: # if user not found or password is wrong
return Response({'Error': "Invalid username/password"}, status="400")
if user.is_authenticated:
print("user is authenticated") # THIS GETS PRINTED
else:
print("User is not authenticated")
Settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
#'rest_framework.authentication.BasicAuthentication',
'Root.authentication.TokenAuthentication.TokenAuthentication'
]
}
The line
if user.is_authenticated:
print("user is authenticated")
Is running everytime when None is being returned.
Any help would be appreciated. Thank you.
Note: If it matters, I'm using PyJwt.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
