2

我想在后端使用带Django-REST frameowrk的Django来认证Native android应用上的用户。我目前使用基于令牌的认证系统。 (More detailsDjango REST HTTP 400获取令牌认证视图时出错

我已经实现了指南中列出的完全相同的过程,以设置令牌认证。

现在我希望我的用户能够获取凭证以换取凭据。我用用下面的代码进行POST请求:

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()); 

然而,当我张贴此对我的Django的后端,用 “views.obtain_auth_token”,我总是这样的错误:

在服务器:

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

响应我回去:

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

我想了解什么是引发此HTTP 400 (错误请求错误)

回答

2

当提供的登录凭证无效时,会显示此错误。

检查如下:

  • 用户存在于数据库和IS_ACTIVE场AUTH_USER表设置为1?
  • 你的密码是否正确?
  • 你的用户在authtoken_token表中有一个标记?
+0

感谢帐户时的密码,我确信它会返回401或403,如果我有一个错误的用户/密码,但事实证明我只是使用旧的信用。 – horriblyUnpythonic 2017-04-06 20:32:40

0

一个常见的错误是,你需要编码创造,如果你正在使用HyperlinkedModelSerializer或ModelSerializer

喜欢这个

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