I was able to do this without using jsOAuth. I overridden my sync
model method to make jQuery ajax calls and set the beforeSend attribute for these calls to create the oauth header in the request. Then, after setting the appropriate attributes on the model (bodies and URLs in particular), all you need to do for PUT / POST is modelInstance.save()
, and the model will take care of itself.
The following are examples in coffeescript.
Model Example:
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 …
Function 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'])
The oauth module I use is the only Netflix created in 2008, which you can find here here . If you cleaned somehow, you can probably find the file by googling javascript oauth "This isn't as useful as you might hope"
. This request may not look like file approval, but I found this to be wrong: the file is very useful.
Other possible stumbling blocks:
- Your model will need a
url
function that returns the URL to send the request to. key
, secret
and realm
are passed to the initialization method of this model and therefore are available in the code shown above.model.body
is an attribute that you will need to set yourself. This is not a basic attribute.- If my example seems to be a bit off, it's because the model I showed here, in fact, I wrote just to make an oauth connection. Then I had models that actually contained data that extend this model. This is why, for example, the ajax
success
call method calls model.success()
. If this model was a one-time one, the ajax call success
method would actually do the job there successfully.