Backbone.js + jsOAuth

发布于 2024-12-09 15:04:09 字数 320 浏览 1 评论 0原文

我正在使用 Backbone.js 构建一个移动应用程序,我需要执行两条腿的 OAuth 来与 REST API 连接。我找到了一个名为 jsOAuth 的库,但不知道如何将其与 Backbone 集成。

我应该重写 同步方法 以包含标头吗?

任何帮助将不胜感激。

I'm building a mobile app with Backbone.js and I need to do a two-legged OAuth to connect with a REST API. I found a library called jsOAuth but not sure how to integrate it with Backbone.

Should I rewrite the sync method to include the headers?

Any help would be appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

笑叹一世浮沉 2024-12-16 15:04:09

我无需使用 jsOAuth 即可完成此操作。我重写了模型的 sync 方法来进行 jquery ajax 调用,并在这些调用上设置 beforeSend 属性以在请求上创建 oauth 标头。然后,在模型上设置适当的属性(具体来说是 body 和 url)后,您只需 modelInstance.save() 即可进行 PUT/POST,并且模型会处理 oauth 本身。

下面的例子是在coffeescript中。

模型示例:

Backbone.Model.extend

    sync: (method, model, options) ->

        switch method
            when "create"
                $.ajax({
                    url: model.url()
                    data: model.body
                    dataType: 'json'
                    cache: false
                    type: 'POST'
                    beforeSend: (xhr, settings) =>
                        auth = @makeAuthHeader(key, secret, settings.url, 'POST', realm)
                        xhr.setRequestHeader('Authorization', auth)
                        xhr.setRequestHeader('Content-Type', 'application/json')
                    success: (data, textStatus) ->
                        model.postSuccess(data, textStatus)
                    error: (e, jqxhr, exception) ->
                        model.postError(e, jqxhr, exception)
                })
            when "update"
                $.ajax({
                    url: model.url()
                    data: model.body
                    …

“makeAuthHeader”函数:

makeAuthHeader: (key, secret, encodedurl, method, realm) ->
    accessor = {consumerSecret: secret, tokenSecret: ""}
    message = {action: encodedurl, method: method, parameters: [["oauth_version", "1.0"],["oauth_consumer_key", key]]}
    OAuth.setTimestampAndNonce(message)
    OAuth.SignatureMethod.sign(message, accessor)
    return OAuth.getAuthorizationHeader(realm, message['parameters'])

我使用的 oauth 模块是 Netflix 在 2008 年创建的模块,您可以找到该模块 此处。如果该文件以某种方式被删除,您可能可以通过谷歌搜索javascript oauth“这并不像您希望的那么有用”来找到该文件。该查询听起来可能不像对该文件的认可,但我发现它是不真实的:该文件非常有用。

其他可能的障碍:

  • 您的模型需要一个 url 函数来返回要发送请求的 URL。
  • keysecretrealm 被传递到该模型的初始化方法中,因此可以在上面显示的代码中访问。
  • model.body 是您必须自己设置的属性。它不是骨干标准属性。
  • 如果我的例子看起来有点不对劲,那是因为我在这里展示的模型实际上是我专门为了进行 oauth 通信而编写的模型。然后,我让实际包含数据的模型扩展了该模型。例如,这就是 ajax 调用的 success 方法调用 model.success() 的原因。如果此模型是一次性的,则 ajax 调用的 success 方法实际上会立即执行成功工作。

I was able to do this without using jsOAuth. I overrode my model's sync method to make jquery ajax calls, and set the beforeSend attribute on those calls to create an oauth header on the request. Then, after setting the appropriate attributes on the model (body and url, specifically), all you have to do to PUT/POST is modelInstance.save(), and the model takes care of the oauth itself.

The below examples are in coffeescript.

Model sample:

Backbone.Model.extend

    sync: (method, model, options) ->

        switch method
            when "create"
                $.ajax({
                    url: model.url()
                    data: model.body
                    dataType: 'json'
                    cache: false
                    type: 'POST'
                    beforeSend: (xhr, settings) =>
                        auth = @makeAuthHeader(key, secret, settings.url, 'POST', realm)
                        xhr.setRequestHeader('Authorization', auth)
                        xhr.setRequestHeader('Content-Type', 'application/json')
                    success: (data, textStatus) ->
                        model.postSuccess(data, textStatus)
                    error: (e, jqxhr, exception) ->
                        model.postError(e, jqxhr, exception)
                })
            when "update"
                $.ajax({
                    url: model.url()
                    data: model.body
                    …

The 'makeAuthHeader` function:

makeAuthHeader: (key, secret, encodedurl, method, realm) ->
    accessor = {consumerSecret: secret, tokenSecret: ""}
    message = {action: encodedurl, method: method, parameters: [["oauth_version", "1.0"],["oauth_consumer_key", key]]}
    OAuth.setTimestampAndNonce(message)
    OAuth.SignatureMethod.sign(message, accessor)
    return OAuth.getAuthorizationHeader(realm, message['parameters'])

The oauth module I used is the one Netflix created in 2008, which you can find here. In case that gets taken down somehow, you can probably find the file by googling javascript oauth "This isn't as useful as you might hope". That query maybe doesn't sound like an endorsement of the file, but I found it to be untrue: the file is very useful.

Other possible stumbling blocks:

  • Your model will need a url function on it that returns the URL to send the request to.
  • key, secret, and realm get passed in to the initialize method of this model, and so are accessible in the code I've shown above.
  • model.body is an attribute you'll have to set yourself. It's not a backbone-standard attribute.
  • If my example seems a bit off, it's because the model I've shown here is actually one I wrote solely for doing oauth communication. I then had my models that actually contained data extend this model. That's why, for instance, the ajax call's success method calls model.success(). If this model had been a one-off, the ajax call's success method would actually perform the success work right there.
风月客 2024-12-16 15:04:09

我想我可能已经在推特上回答了这个问题。

jsOAuth 1.x 无法轻松插入 jQuery,因此是骨干。然而,自从我在 Twitter 上回答以来,已经取得了一些进展。

jsOAuth 2.0,正在开发中,实现了一个类似 XHR 的接口,这样你就可以像这样使用它:

jQuery.ajaxSettings.xhr =  function () {
    var xhr =  new OAuthRequest;
    xhr.consumerKey = consumerKey;
    xhr.consumerSecret = consumerSecret;
    xhr.accessTokenKey = accessTokenKey;
    xhr.accessTokenSecret = accessTokenSecret;

    return xhr;
};

如您所见,直接推入 jQuery 作为它使用的 XHR 对象。

I think I may have answered this one on Twitter.

jsOAuth 1.x cant be plugged into jQuery easily and so therefore backbone. However there has been some progress since my answer on Twitter.

jsOAuth 2.0, in development, implements a XHR like interface so that you could use it like this:

jQuery.ajaxSettings.xhr =  function () {
    var xhr =  new OAuthRequest;
    xhr.consumerKey = consumerKey;
    xhr.consumerSecret = consumerSecret;
    xhr.accessTokenKey = accessTokenKey;
    xhr.accessTokenSecret = accessTokenSecret;

    return xhr;
};

As you can see, pushed directly into jQuery as the XHR object it uses.

触ぅ动初心 2024-12-16 15:04:09

为什么你不尝试使用 $.ajaxPrefilter (http://api.jquery.com/jQuery.ajaxPrefilter/)

你可以添加一个预过滤器,检查 url 是否适用于此 oauth 连接的范围,如果是,那么更改标头、添加授权标头或更改查询参数。

Why you don't try with $.ajaxPrefilter (http://api.jquery.com/jQuery.ajaxPrefilter/)

You can add a prefilter, check if the url is for the scope of this oauth connection, and if it's, then change headers, add authorization header or change query params.

如梦亦如幻 2024-12-16 15:04:09

您可能还想查看Backbone 的 OAuth 2.0 插件

You might also want to look at this OAuth 2.0 plugin for Backbone.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文