【问题标题】:How to use Basic Auth with libsoup via Gjs如何通过 Gjs 将 Basic Auth 与 libsoup 一起使用
【发布时间】:2017-02-17 11:17:21
【问题描述】:

我正在尝试使用令牌查询 github 的 api。 Github 的 api 接受生成的令牌,前提是它们作为基本身份验证标头发送。

如果在没有身份验证的情况下进行调用,API 不会返回 HTTP 401,这意味着如果想要使用基本身份验证查询他们的 api,则必须先发制人地填写标头,而不是进行往返。

我现在正在尝试使用 libsoup 和 Gjs 查询 API。

我注意到 SoupAuthManager 有一个似乎完全符合我需要的功能 (soup_auth_manager_use_auth here) 但找不到调用它的方法。

这可用于“预加载” manager 的身份验证缓存,以避免在您提前知道将返回 401 响应的情况下额外的 HTTP 往返

这是我目前使用的,但它不起作用,因为 SoupAuthManager 是会话的私有对象;因此对程序的实际行为没有影响

let httpSession = new Soup.Session();
let authUri = new Soup.URI(url);
authUri.set_user(this.handle);
authUri.set_password(this.token);
let message = new Soup.Message({method: 'GET', uri: authUri});

let authManager = new Soup.AuthManager();
let auth = new Soup.AuthBasic({host: 'api.github.com', realm: 'Github Api'});

authManager.use_auth(authUri, auth);
httpSession.queue_message(message, ...);

我可以使用其他方法在第一次旅行中强制使用基本身份验证吗?还是我可以从 gjs 中使用其他库来调用 github 的 API 并强制进行基本身份验证?

【问题讨论】:

    标签: gnome gobject gnome-shell-extensions gjs libsoup


    【解决方案1】:

    我找到了解决方案。要将授权链接到会话,可以使用 add_feature 函数。现在这是定义here 但结果直接调用它不起作用

    this._httpSession.add_feature(authManager)
    

    相反,如果这样调用它似乎可以工作:

    Soup.Session.prototype.add_feature.call(httpSession, authManager);
    

    最后,github api 拒绝任何没有用户代理的调用,所以我添加了以下内容:

    httpSession.user_agent = 'blah'
    

    最终代码如下:

    let httpSession = new Soup.Session();
    httpSession.user_agent = 'blah'
    let authUri = new Soup.URI(url);
    authUri.set_user(this.handle);
    authUri.set_password(this.token);
    let message = new Soup.Message({method: 'GET', uri: authUri});
    
    let authManager = new Soup.AuthManager();
    let auth = new Soup.AuthBasic({host: 'api.github.com', realm: 'Github Api'});
    
    Soup.Session.prototype.add_feature.call(httpSession, authManager);
    httpSession.queue_message(message, function() {...});
    

    【讨论】:

      猜你喜欢
      • 2013-09-23
      • 2019-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-23
      • 1970-01-01
      • 2021-05-17
      • 2019-09-13
      相关资源
      最近更新 更多