Django REST HTTP 400 Error on Getting Token Authentication View

别说谁变了你拦得住时间么 提交于 2019-12-23 19:31:09

问题


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-toekn-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)


回答1:


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?.



回答2:


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}}


来源:https://stackoverflow.com/questions/28347200/django-rest-http-400-error-on-getting-token-authentication-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!