Consume a webservice with basic authentication using Soup

好久不见. 提交于 2019-12-25 07:05:54

问题


As part of a gnome-shell extension, I try to consume a webservice using xmlrpc. The webservice expects a basic authentication header. Using Soup, I got the following code (basically a blueprint from the great openweather extension):

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

I am using Soup for building up the connection. The authenticate signal is executed before the queue-callback is executed.

Still, in the beginning within the callback, the response_body holded the status code 401 instead of the expected authorization. The given credentials where incorrect.After correcting this, the call went through. However, you always need two calls to the provider this way: first to get the information it uses BasicAuth, and the second to actually do the call.

Is there a way to give the authentication information directly with the first call?


回答1:


It's possible to add the authorization directly into the request header

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

This prevents a first request without auth header and also allows use of REST services that don't return the correct status code on unauthorized requests and forward to a login page instead.



来源:https://stackoverflow.com/questions/35341006/consume-a-webservice-with-basic-authentication-using-soup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!