簡體   English   中英

使用Soup使用具有基本身份驗證的Web服務

[英]Consume a webservice with basic authentication using Soup

作為gnome-shell擴展的一部分,我嘗試使用xmlrpc使用Web服務。 Web服務需要一個基本的身份驗證標頭。 使用湯,我得到了以下代碼(基本上是偉大的openweather擴展的藍圖):

function load_json_async() {

    if (_httpSession === undefined) {
       _httpSession = new Soup.Session();
    } else {
        // abort previous requests.
        _httpSession.abort();
    }

    let message = Soup.xmlrpc_message_new (
         "https://api.sipgate.net/RPC2", 
         "samurai.BalanceGet", 
         new GLib.Variant('()',1.0)
     )

    _httpSession.connect('authenticate', 
       Lang.bind(
         this,function(session,message, auth,retryFlag){
           auth.authenticate("xxxxx","xxxxx");
         }
       )
     )

    _httpSession.queue_message(
       message, 
       Lang.bind(this, 
           function(_httpSession, message) {
            try {
              if (!message.response_body.data) {
                log("hello1 "+message.response_body.status)
                return;
              } else {
                log("got message-status:"+message.status_code)
              }
              log(message.response_body.data)
            } catch (e) {
              log("exception:"+e)                
              return;
            }
       return;
    }));
    return;
}

我正在使用Soup建立連接。 認證信號在執行隊列回調之前執行。

仍然在回調的開始部分,response_body保留狀態代碼401而不是預期的授權。 給定的憑據不正確。更正后,呼叫繼續進行。 但是,您總是需要通過這種方式對提供程序進行兩次調用:首先是獲取它使用BasicAuth的信息,其次是實際進行調用。

有沒有辦法在第一次呼叫時直接提供身份驗證信息?

可以將授權直接添加到請求標頭中

let auth = new Soup.AuthBasic()
auth.authenticate("xxx","xxx");
message.request_headers.append("Authorization",auth.get_authorization(message))

這樣可以防止沒有auth標頭的第一個請求,還允許使用REST服務,該服務不會在未授權的請求上返回正確的狀態代碼,而是轉發到登錄頁面。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM