2016-03-15 26 views
3

我想在我的web應用程序中集成django-rest-auth軟件包。到目前爲止,我可以註冊用戶,發送密碼重置電子郵件並使用django-rest-auth軟件包提供的API登錄。如何在Django-rest-auth中驗證請求?

現在,當我發送登錄請求時,它會在成功驗證後返回「令牌」。

如何在更多請求中發送身份驗證令牌?例如,我試圖使用GET /rest-auth/user來獲取用戶,但它給了我一個回覆Authentication credentials not provided。我曾嘗試通過HTTP基本身份驗證(Base64編碼令牌作爲用戶名並將密碼保留爲空)傳遞令牌。我仍然無法工作。

任何人都知道我應該如何在請求中傳遞此令牌?

回答

2

如果你想使用Token Authentication你必須設置Authorization HTTP頭。從文檔:

對於客戶端進行身份驗證,令牌密鑰應包括在Authorization HTTP標頭中。關鍵字應以字符串文字「Token」爲前綴,用空格分隔兩個字符串。例如:

授權:令牌9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b

在AJAX調用,你可以像這樣的標題:

$.ajax({ 
    type: 'POST', 
    url: url, 
    beforeSend: function (request) 
    { 
     request.setRequestHeader("Authorization", "Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b"); 
    }, 
}); 
+0

即使這不起作用。仍然收到迴應:'{「detail」:「未提供身份驗證憑據。」} –

+0

您配置了'AUTHENTICATION_CLASSES'嗎? (http://www.django-rest-framework.org/api-guide/authentication/#setting-the-authentication-scheme)並添加了'TokenAuthentication'? – ilse2005

1

HI 您需要在標頭中發送令牌

enter image description here

$.ajax({ 
      type:"POST", 
      beforeSend: function (request) 
      { 
       request.setRequestHeader("Authority", 'Bearer 33a95862173cc0565fe502eb062b2e7c67e23a3a'); 
      }, 

和在Django代碼使用

user = request.user 
if user: 
return "User token verified" 
elif : 
return "User token not verified" 

在Django automaticaly發現令牌頭和使用代幣讀取用戶數據。