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