Reputation: 395
I'm having trouble understanding how to get authentication to work. I have set up a basic api, and I am trying to get any type of authentication to work (Basic Authentication to start with). But no matter what I do, I am able to retrieve information from the database (using Postman) without entering a username or password. What am I doing wrong?
Here is my class:
class User(models.Model):
birthdate = models.DateField()
gender = models.CharField(
max_length=1,
choices=(('M', 'Male'), ('F', 'Female'), ('O', 'Other'), ('U', 'Unspecified'))
)
join_date = models.DateField(auto_now_add=True)
username = models.CharField(max_length=25, unique=True)
password = models.CharField(max_length=25,)
Here is my view:
def user_tester(request):
permission_classes = (IsAuthenticated,)
if request.method == 'GET':
objs = User.objects.all()
serializer = UserSerializer(objs, many=True)
return JsonResponse(serializer.data, safe=False)
Here are the relevant settings:
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
)
}
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
Please advise on what I am doing wrong. I have some experience with Django, but none at all with authentication or permissions.
Upvotes: 2
Views: 3668
Reputation: 126
Instead of using: permission_classes = (IsAuthenticated,)
,
You should try the decorator before the definition of your "user_tester" method like:
from rest_framework.decorators import api_view, permission_classes
@api_view(['GET'])
@permission_classes((IsAuthenticated, ))
def user_tester(request):
objs = User.objects.all()
serializer = UserSerializer(objs, many=True)
return JsonResponse(serializer.data, safe=False)
Upvotes: 11
Reputation: 53774
The following line is dead code:
permission_classes = (IsAuthenticated,)
You are not creating a view by extending any of the django rest framework classes. it's only classes such as APIView
that have a permissions_classes property that you can use to control authentiation. What you have is a simple function based view that merely returns a json. You are not even using django-rest-framework here. Your serialization code can be replaced by to_dict
and json.dumps
If you want to continue with the current approach, decorate your FBV as
@api_view(['GET'])
@permission_classes((IsAuthenticated, ))
but with DRF you are better off with a CBV approach.
Upvotes: 2