ng-token-auth不会持久化

时间:2015-05-09 21:51:49

标签: javascript ruby-on-rails angularjs authentication devise

我现在使用ng-token-auth和rails'devise-token-auth提供了一个非常简单的应用程序。它运行正常,$ auth方法运行良好(例如,登录)。但是,在页面刷新时,access-token不会保留,也不会使用ipCookie写入cookie。

我的rails应用正在转发正确的标题,如下所示:

Access-Control-Allow-Credentials:true
Access-Control-Allow-Methods:GET, POST, DELETE, PUT, OPTIONS, HEAD
Access-Control-Allow-Origin:http://localhost
Access-Control-Expose-Headers:
Access-Control-Max-Age:0
access-token:XXXXXXXXXXXXXX
Cache-Control:max-age=0, private, must-revalidate
client:nYMXLxnuO7BIGZkdXkZ_Xg
Connection:Keep-Alive
Content-Type:application/json; charset=utf-8
Date:Sat, 09 May 2015 21:41:56 GMT
ETag:"c16291f5079691a2528d5a7876627ede"
expiry:1431294116
Keep-Alive:timeout=5, max=99
Server:Apache/2.4.10 (Unix) PHP/5.5.20
token-type:Bearer
Transfer-Encoding:chunked
uid:tester53@mailinator.com
Vary:Origin
X-Content-Type-Options:nosniff
X-Frame-Options:SAMEORIGIN
X-Request-Id:2b224904-944c-48f7-aa4e-d0407e26e893
X-Runtime:0.230242
X-XSS-Protection:1; mode=block

但当它通过updateHeadersFromResponse ng-token-auth方法运行时,标题返回null - 特别是在ng-token-auth.js的第588行

updateHeadersFromResponse = function($auth, resp) {
  var key, newHeaders, val, _ref;
  newHeaders = {};
  _ref = $auth.getConfig().tokenFormat;
  for (key in _ref) {
    val = _ref[key];
    if (resp.headers(key)) {
      newHeaders[key] = resp.headers(key);
    }
  }
  if (tokenIsCurrent($auth, newHeaders)) {
    return $auth.setAuthHeaders(newHeaders);
  }
};

有没有人遇到过这个?为什么不将标头传递给此$httpProvider方法?

1 个答案:

答案 0 :(得分:13)

我在这篇文章Angular.js saying custom HTTP response header is null

中找到了答案

我使用的是多域设置,因此API域需要在CORS配置中有一些额外的公开标头。所以在rails-cors gem中我为access-token添加了一个额外的公开值:

config.middleware.insert_before 0, "Rack::Cors" do
  allow do
    origins 'api.com'

    resource '*',
      :headers => :any,
      :methods => [:get, :post, :delete, :put, :options, :head],
      :expose  => ['access-token', 'expiry', 'token-type', 'uid', 'client'],
      :max_age => 0
  end
end

更新:公开角度所需的所有字段,而不只是一个使其起作用的字段。