2

I want to implement the most Basic Authentication in my django-rest-framework app, and I keep on getting a {"detail":"Invalid username/password."} response (sometimes 401 and sometimes 403).

Here is my UserViewSet code:

class UserViewSet(mixins.CreateModelMixin,
               mixins.RetrieveModelMixin,
               mixins.ListModelMixin,
               viewsets.GenericViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = (permissions.IsAuthenticated, )

In the settings.py I don't have anything about authentication, just the default stuff.

my android code:

getUsers = new HttpGet("http://10.100.102.10:8000/users/");
String basicAuth = "Basic " + Base64.encodeToString("testingUser:123".getBytes(), Base64.NO_WRAP);
getUsers.setHeader("Authorization", basicAuth);

// executing the request
response = httpClient.execute((HttpUriRequest) request);
result = EntityUtils.toString(response.getEntity());
responseCode = response.getStatusLine().getStatusCode();

The user does exist in the Database - as you can see in the screen shot.

I am adding a screen shot of the json I am getting from the http://10.100.102.10:8000/users/ url in the browser, (after I removed the permission_classes = (permissions.IsAuthenticated, )) - meaning everyone can acces).

enter image description here

This is the UserSerializer:

class UserSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', )

        def create(self, validated_data):
            user = User.objects.create_user(
                first_name = validated_data['first_name'],
                last_name = validated_data['last_name'],
                username = validated_data['username'],
                password = validated_data['password'],
            )
            return user

What is wrong with my code? any reason this doesn't work?

thanks!

1 Answer 1

0

You are sending the authentication details as a part of Authorization Header which is Token Authentication. The default authentication scheme for Django Rest Framework is Session Authentication. You need to add TokenAuthentication to 'DEFAULT_AUTHENTICATION_CLASSES' in your settings.

REST_FRAMEWORK = {

    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication'
    ),
 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.