【问题标题】:Consume a webservice with basic authentication using Soup使用 Soup 使用具有基本身份验证的 Web 服务
【发布时间】:2016-02-11 13:43:38
【问题描述】:

作为 gnome-shell 扩展的一部分,我尝试使用 xmlrpc 使用 Web 服务。 Web 服务需要一个基本的身份验证标头。使用 Soup,我得到了以下代码(基本上是来自伟大的 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 的信息,第二次实际进行调用。

有没有办法在第一次调用时直接提供身份验证信息?

【问题讨论】:

    标签: javascript gtk gnome-shell gnome-shell-extensions gjs


    【解决方案1】:

    可以直接在请求头中添加授权

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

    这可以防止没有 auth 标头的第一个请求,还允许使用 REST 服务,这些服务不会在未经授权的请求上返回正确的状态代码,而是转发到登录页面。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      相关资源
      最近更新 更多