【发布时间】:2014-09-30 03:23:01
【问题描述】:
我正在开发一个 Ionic 移动应用程序,以使用 JSON API 与我的后端 Rails 服务器通信。如果第一个GET 请求返回一个名为XSRF-TOKEN 的cookie,我已经通过在POST 请求上发送标头X-XSRF-TOKEN 来阅读AngularJS will automatically handle XSRF protection。
我已将我的 Rails application_controller.rb 更新为如下:
class ApplicationController < ActionController::Base
protect_from_forgery
after_filter :set_access_control_headers
after_filter :set_csrf_cookie_for_ng
def after_sign_in_path_for(resource)
main_path
end
def after_sign_out_path_for(resource)
login_path
end
##
# Sets headers to support AJAX Cross-Origin Resource Sharing.
# This is only needed for testing within browser (i.e. mobile apps do not need it).
##
def set_access_control_headers
# hosts who can make AJAX requests
headers['Access-Control-Allow-Origin'] = 'http://localhost:8100'
headers['Access-Control-Request-Method'] = '*'
headers['Access-Control-Allow-Headers'] = 'accept, content-type, x-xsrf-token'
# allow clients to use cookies to track session state
headers['Access-Control-Allow-Credentials'] = 'true'
end
##
# Sets a cookie containing an XSRF token. This should be returned by the
# client as a header field named 'X-XSRF-TOKEN'
def set_csrf_cookie_for_ng
cookies['XSRF-TOKEN'] = form_authenticity_token if protect_against_forgery?
end
protected
def verified_request?
super || form_authenticity_token == request.headers['X-XSRF-TOKEN']
end
end
AngularJS 代码是:
$http({
method: 'POST',
url: $scope.getBackendUrl() + '/reports.json',
params: params,
withCredentials: true,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
我已经进行了Wireshark 转储,并且可以看到 Rails 服务器正在通过 Cookie 发送(我可以在 AngularJS 中读取它)。但是,AngularJS 没有将标头 X-XSRF-TOKEN 发送到我的后端 Rails 服务器,导致 WARNING: Can't verify CSRF token authenticity。
我已经阅读了一堆 SO 问题,但无济于事。例如。 XSRF headers not being set in AngularJS
我添加了 CORS 标头内容,以便我可以从 Chrome 进行测试。同样,我可以看到来自服务器的 cookie,但没有发回标头。但是,cookie 在 'Cookie' 标头字段中被发送回。
任何人都可以看到我缺少什么,或者我可以尝试解决这个问题吗?我目前正在解析请求中的Cookie 标头字段以提取令牌并检查真实性以在测试时解决问题。
def verified_request?
# should just need to do the below, but for some reason AngularJS is not setting 'X-XSRF-TOKEN'
#super || form_authenticity_token == request.headers['X-XSRF-TOKEN']
if(super)
true
else
cookie = request.headers['Cookie'] || ""
value = cookie.nil? ? "" : CGI.unescape( cookie.gsub(/.*XSRF-TOKEN=(.+);.*/, '\1') )
form_authenticity_token == value
end
end
版本:
- Rails 3.2.3
- Ionic 1.1.6(在 AngularJS 中捆绑)
【问题讨论】:
标签: ruby-on-rails angularjs cors ionic-framework