如何在 Rails、Devise 和 Backbone.js 中使用令牌认证? [英] How use token authentication with Rails, Devise and Backbone.js?
问题描述
我正在尝试在客户端使用 PhoneGap、jQuery Mobile 和 Backbone.js 构建移动应用程序 - 在服务器端运行 Rails 3 JSON API.
我知道如何在通过身份验证后从服务器获取令牌,但我不知道如何将token_auth"键/值附加到 Backbone.js 将向我的服务器发出的所有 AJAX 请求.>
这是我目前的流程:
- 用户在某些表单字段中输入并点击登录"
- Backbone 使用电子邮件和密码信息创建一个新的 Player 对象.
- 我运行了一个 Player.authenticate,将令牌设置为 AUTHENTICATION_TOKEN
- 此后的所有请求都应附加auth_token=" + AUTHENTICATION_TOKEN
我看过http://documentcloud.github.com/backbone/#Sync 可能会覆盖 AJAX 调用 - 但对于这个简单的任务来说,这似乎非常极端.
有人有运行 Devise token_authentication 和 Backbone.js 的经验吗?
为什么不将它附加到您的所有 jquery ajax 请求中.它会将 auth_token 添加到您通过 jQuery 进行的所有 ajax 调用中.当直接使用 jQuery ajax(或这样做的库)时,这可能很有用.但这也可能是一个安全问题(当您对其他站点进行 ajax 调用时......).
//这是未经测试的$.ajaxSetup({ beforeSend : function(xhr, settings){//只是因为 auth_token 是私有信息如果(!settings.crossDomain){//解析数据对象var dataobj = JSON.parse(xhr.data);//向数据对象添加身份验证令牌dataobj.auth_token = AUTHENTICATION_TOKEN;//将数据对象保存到 jqXHR 对象中xhr.data = JSON.stringify(dataobj);}}});
<小时>
另一种方法可能是将该令牌写入标头并在服务器端对其进行处理:
//那不漂亮$.ajaxSetup({ headers : { "auth_token" : AUTHENTICATION_TOKEN } });
I'm trying to build a mobile application with PhoneGap, jQuery Mobile and Backbone.js on the client-side - with a Rails 3 JSON API running server-side.
I know how to fetch the token from the server after being authenticated, but I don't know how to append the "token_auth" key/value to all the AJAX-requests Backbone.js will make to my server.
Here's my flow at the moment:
- User types in some form fields and hits "Log in"
- Backbone creates a new Player object with the email and password info.
- I run a Player.authenticate that sets the token to AUTHENTICATION_TOKEN
- All requests after this should append "auth_token=" + AUTHENTICATION_TOKEN
I've looked at http://documentcloud.github.com/backbone/#Sync for maybe overriding the AJAX calls - but that seems quite extreme for this simple task.
Does anyone have any experience with running Devise token_authentication and Backbone.js?
Why don't append it to all of your jquery ajax requests. It will add the auth_token to all of your ajax calls over jQuery. That might be useful when working directly with jQuery ajax (or libs that do so). But this might be a security issue as well (when you have ajax calls to other sites...).
// this is untested
$.ajaxSetup({ beforeSend : function(xhr, settings){
// just because the auth_token is a private information
if(!settings.crossDomain) {
// parse data object
var dataobj = JSON.parse(xhr.data);
// add authentication token to the data object
dataobj.auth_token = AUTHENTICATION_TOKEN;
// save the dataobject into the jqXHR object
xhr.data = JSON.stringify(dataobj);
}
}});
Another approach may be to write that token into the header and process it on the server side:
// thats not beautiful
$.ajaxSetup({ headers : { "auth_token" : AUTHENTICATION_TOKEN } });
这篇关于如何在 Rails、Devise 和 Backbone.js 中使用令牌认证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!