Devise_token_auth - 无法运行控制器操作

时间:2016-03-03 15:46:10

标签: ruby-on-rails swift devise token alamofire

我目前正在构建一个与ruby-on-rails api通信的iOS应用程序。 api的用户管理(sign_in,sign_out,...)部分由devise_token_auth gem处理。

我也在使用Alamofire来运行HTTP次请求。

我目前正在测试两个apis:

  1. POST /api/auth/sign_in(.:format) devise_token_auth/sessions#create
  2. POST /api/posts(.:format) api/posts#create
  3. 第一个api用于登录,而第二个用于创建帖子。仅供参考,在我的posts_controller中,我使用before_action :authenticate_user!来阻止未经过身份验证的用户创建帖子。

    这是我想要做的:

    1. 从客户端登录(iOS应用) - > sign_in api返回访问令牌
    2. 使用访问令牌从客户端创建帖子。
    3. 我设法使用以下代码获取访问令牌:

      let parameters = [
              "email":"omar@omar.com",
              "password":"password"]
      
      Alamofire.request(.POST, "http://localhost:3000/api/auth/sign_in", parameters: parameters)
              .responseJSON { response in
                  // get my access token and store it.
      }
      

      当我尝试创建帖子(第2部分)时,我就是这样做的:

      let headers = ["access-token":"<my-token-value>",
                         "token-type":   "Bearer",
                         "uid":"omar@omar.com"]
      
      let parameters = [
              "title":"this is a title",
              "body":"this is a body"]
      
      Alamofire.request(.POST, "http://localhost:3000/api/posts", parameters: parameters, headers: headers)
              .responseJSON { response in
                  print(response.response) // URL response
      }
      

      打印回复时,我得到的是:

      Optional(<NSHTTPURLResponse: 0x7fe422f2b670> { URL: http://localhost:3000/api/posts } { status code: 401, headers {
      "Cache-Control" = "no-cache";
      Connection = "Keep-Alive";
      "Content-Length" = 37;
      "Content-Type" = "application/json; charset=utf-8";
      Date = "Thu, 03 Mar 2016 15:03:27 GMT";
      Server = "WEBrick/1.3.1 (Ruby/2.2.1/2015-02-26)";
      "Set-Cookie" = "request_method=POST; path=/";
      Vary = Origin;
      "X-Content-Type-Options" = nosniff;
      "X-Frame-Options" = SAMEORIGIN;
      "X-Request-Id" = "82a88799-3fac-42e0-bd01-db5b7e24fcda";
      "X-Runtime" = "0.045969";
      "X-Xss-Protection" = "1; mode=block";
      } })
      

      另外,在Rails服务器日志上:

      Filter chain halted as :authenticate_user! rendered or redirected
      

      Completed 401 Unauthorized in 15ms (Views: 0.8ms | ActiveRecord: 4.4ms)

      有谁知道错误的来源?

1 个答案:

答案 0 :(得分:1)

我终于找到了解决方案。除了期待access-tokentoken-typeuid之外,我的API还期望标头中包含client ID。此client ID在sign_in请求响应中发送。