繁体   English   中英

Devise Token Auth-如何从Rails控制台访问受保护的路由

[英]Devise Token Auth - How to access a protected route from the Rails console

我正在使用Angularjs,Rails,devise_token_auth和ng-token-auth,并且试图从控制台登录用户。

我不知道如何获得蒂姆·桑特福德在本文中提到的302。

这仍然适用于Rails 4还是200响应仍然表示我没有成功登录?

我做了Brian Deterling提到的发帖请求,得到了:

Started POST "/api/private/auth/sign_in" for 127.0.0.1 at 2016-03-30 13:36:44 -0500
Processing by DeviseTokenAuth::SessionsController#create as JSON
Parameters: {"email"=>"freud@iron.com", "password"=>"[FILTERED]"}
...
(9.9ms)  COMMIT
Completed 200 OK in 361ms (Views: 0.4ms | ActiveRecord: 23.3ms)
=> 200

因此,除了200而不是Tim Santeford提到的302响应之外,我似乎已成功登录。

然后,我执行app.session,它看起来像工作。

irb(main):026:0> app.session
=> #<ActionDispatch::Request::Session:0x007fe7a1898358 @by=#<ActionDispatch::Session::CookieStore:0x007fe79ed821f0
...
@delegate={"session_id"=>"4346eb0ee9fc8a8e95735d1e3f2adc28"}, @loaded=true, @exists=true>

然后,我执行一个app.controller.current_user,这看起来也可以使用。

irb(main):027:0> app.controller.current_user
=> #<User id: 233, provider: "email", uid: "freud@iron.com", encrypted_password: "$2a$10$v2fapiZCH5b5XN.ji57KgOJ0SJfVHzJByYPFpVCeU1j...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 32, current_sign_in_at: "2016-03-30 18:36:44", last_sign_in_at: "2016-03-30 18:01:00", current_sign_in_ip: "127.0.0.1",

但是当我输入受保护的路由时,我得到

irb(main):029:0> app.get('/api/private/rfqs')
Started GET "/api/private/rfqs" for 127.0.0.1 at 2016-03-30 14:11:21 -0500
Processing by Api::RfqsController#index as JSON
Filter chain halted as :authenticate_user! rendered or redirected
Completed 401 Unauthorized in 1ms (Views: 0.2ms | ActiveRecord: 0.0ms)
=> 401

...如果在此请求之后,我再次执行app.session和app.controller.current_user

irb(main):030:0> app.session
=> #<ActionDispatch::Request::Session:0x7fe7a1213910 not yet loaded>

irb(main):031:0> app.controller.current_user
=> nil

有人可以告诉我为什么会这样吗?

首先,您应该知道Devise不再管理用户的会话。 这就是为什么建议使用devise_token_auth 另外,由于您使用的是devise_token_auth gem,因此所引用的答案也不是为您提供帮助的理想选择。

错误Filter chain halted as :authenticate_user! rendered or redirected Filter chain halted as :authenticate_user! rendered or redirected意味着您必须登录才能运行Api::RfqsController#index控制器操作。 登录时,您在headers收到以下信息:

"access-token": "my-access-token",
"token-type":   "Bearer",
"client":       "my-client-id",
"expiry":       "yyyyy",
"uid":          "freud@iron.com"

为了使app.get('/api/private/rfqs')起作用,您需要添加查询标头:

  1. access-token
  2. uid
  3. token-type (值为Bearer
  4. client

我建议您使用Postman软件测试您的Rails API。 比使用控制台更有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM