silent_grave
silent_grave

Reputation: 638

Django REST HTTP 400 Error on Getting Token Authentication View

I want to use Django with Django-REST frameowrk on backend to authenticate users on Native android app. I am currently using Token based auth system. (More details)

I have implemented exact same procedure listed by the guide, to setup up the Token Authentication.

Now I want my user to be able to obtain token in exchange for credentials. I use make a POST request using following code:

      JSONObject cred = new JSONObject();

            try {
                cred.put("password",mPassword);
                cred.put("username",mEmail);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            try {
               
                HttpClient httpClient = new DefaultHttpClient();

                HttpPost httpPost = new HttpPost(Common.getServerUrl()+"/api-token-auth/");
                StringEntity credentials = new StringEntity( cred.toString());
                credentials.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                httpPost.setHeader("Accept", "application/json");
                httpPost.setHeader("Content-type", "application/json");
                httpPost.setEntity(credentials);
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();

                // Read content & Log
                inputStream = httpEntity.getContent();
                Log.i("Asynctask", cred .toString());
...

However, when I post this to my django backend for "views.obtain_auth_token", I always this error:

On server:

"POST /api-token-auth/ HTTP/1.1 400" 

Response I get back:

{"non_field_errors":["Unable to log in with provided credentials."]}

I wish to understand what is throwing this HTTP 400 (Bad Request error)

Upvotes: 6

Views: 7643

Answers (2)

superlee
superlee

Reputation: 836

A Common error is that you need to encode the password when creating an account if you are using HyperlinkedModelSerializer or ModelSerializer

Like this

class UserSerializer(serializers.HyperlinkedModelSerializer):
  def create(self, validated_data):
    user = User(
        email=validated_data['email'],
        username=validated_data['username']
    )
    user.set_password(validated_data['password'])
    user.save()
    return user

  class Meta:
    model = User
    fields = ('url', 'username', 'password', 'email', 'groups')
    extra_kwargs = {'password': {'write_only': True}}

Upvotes: 3

sc3w
sc3w

Reputation: 1164

This error appears when the provided login credentials are not valid.

Check the followings:

  • your user exists in the auth_user table of the database and the is_active field is set to 1?
  • your password is correct?
  • your user has a token in the authtoken_token table?.

Upvotes: 5

Related Questions