2010-07-21 103 views
2

我目前有一個Palm WebOS應用程序,它使用Ajax.Request使用基本身份驗證連接到Web服務。要發送用戶名和密碼,我只是簡單地將它包含在URL(即http://username:[email protected]:port/)中,它工作得非常好,當密碼包含除字母數字字符之外的任何內容時(例如,最近有一個用戶發郵件給我, 「和他的密碼中的」&「,並且他無法連接,因爲這些符號沒有針對url進行正確解析)。有沒有辦法在url中發送憑據,以便我可以允許用戶在密碼中使用除字母數字之外的其他內容?通過Ajax.Request使用身份驗證

var username = cookie.get().servers[this.serverIndex].username; 
    var password = cookie.get().servers[this.serverIndex].password; 
    this.auth = 'Basic ' + Base64.encode(username + ':' + password); 
    var baseUrl = 'http://' + url + ':' + port + '/gui/'; 
    this.baseUrl = baseUrl; 


    var request = new Ajax.Request(this.tokenUrl, { 
     method: 'get', 
     timeout: 2000, 
     headers: { 
      Authorization: this.auth 
     }, 
     onSuccess: successFunc, 
     onFailure: this.failure.bind(this) 
    }); 

反應是(我刪除出於安全原因的網址):

{"request": {"options": {"method": "get", "asynchronous": true, "contentType": "application/x-www-form-urlencoded", "encoding": "UTF-8", "parameters": {}, "evalJSON": true, "evalJS": true, "timeout": 2000, "headers": {"Authorization": "Basic c3VubW9yZ3VzOmZyb2dneUAlMjY="}}, "transport": {"readyState": 4, "onloadstart": null, "withCredentials": false, "onerror": null, "onabort": null, "status": 401, "responseXML": null, "onload": null, "onprogress": null, "upload": {"onloadstart": null, "onabort": null, "onerror": null, "onload": null, "onprogress": null}, "statusText": "", "responseText": "", "UNSENT": 0, "OPENED": 1, "HEADERS_RECEIVED": 2, "LOADING": 3, "DONE": 4}, "url": "" 

回答

3

發送基本身份驗證信息與標題: http://coderseye.com/2007/how-to-do-http-basic-auth-in-ajax.html

var auth = 'Basic ' + Base64.encode(user + ':' + pass); 
Ext.Ajax.request({ 
    url : url, 
    method : 'GET', 
    headers : { Authorization : auth } 
}); 
+0

好吧,試過了,我得到了一個401錯誤...用我的Ajax.Request調用和我的回覆編輯了我的帖子... – 2010-07-21 12:40:25

+2

好吧,我明白了!我不得不將'header'改爲'requestHeaders',並且一切都很好!謝謝! – 2010-07-21 13:06:23

0

你可以試着編碼的用戶名和密碼,他們開始使用encodeURIComponent發送之前。

雖然更一般,你在IE8中測試過這種方法嗎?因爲它不再適用於普通請求 - 出於安全原因,username:[email protected]方案已被禁用。

雖然它可能是,但它們仍然被允許在Ajax請求中。

+0

我試圖使用encodeURIComponent,它轉換的「&」,而不是「@」,所以它仍然沒有奏效。另外,不需要在IE8中測試它...它是一個Palm WebOS應用程序,所以它只會在那裏運行... – 2010-07-21 12:13:12

+0

@sunmorgus奇怪 - 它絕對應該編碼'@'。但也許它會被解釋爲URL的一部分。 – 2010-07-21 12:16:25