2016-03-03 34 views
1

我目前正在構建一個iOS應用程序,它與ruby-on-rails API進行通信。 api的用戶管理(sign_in,sign_out,...)部分由devise_token_auth gem處理。我也使用Alamofire來運行HTTP請求。Devise_token_auth - 無法運行控制器動作

我目前正在測試兩個API:

  1. POST /api/auth/sign_in(.:format) devise_token_auth/sessions#create
  2. POST /api/posts(.:format) api/posts#create

第一API是用來登錄,而第二個創造職位。僅供參考,在我的posts_controller中,我使用的是before_action :authenticate_user!以防止未經身份驗證的用戶創建帖子。

這是我想做的事:

  1. 登錄從客戶端(iOS應用) - >在sign_in API返回的訪問令牌
  2. 使用創建從客戶端後訪問令牌。

我設法獲得訪問令牌使用此代碼:

let parameters = [ 
     "email":"[email protected]", 
     "password":"password"] 

Alamofire.request(.POST, "http://localhost:3000/api/auth/sign_in", parameters: parameters) 
     .responseJSON { response in 
      // get my access token and store it. 
} 

當我嘗試創建一個職位(第二部分),這裏是我做過什麼:

let headers = ["access-token":"<my-token-value>", 
        "token-type": "Bearer", 
        "uid":"[email protected]"] 

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 serv呃日誌:

Filter chain halted as :authenticate_user! rendered or redirected 

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

有誰知道錯誤是哪裏來的?

+0

您是否嘗試過auth_token而不是訪問令牌?我的導軌應用與設計使用auth_token,我認爲默認 –

+0

它沒有工作..它是訪問令牌根據https://github.com/lynndylanhurley/devise_token_auth#token-header-format –

+0

也許你應該嘗試攔截你的POST(使用Fiddler或類似的方法)來查看哪些頭文件實際上被髮送到你的服務器。 –

回答

1

我終於找到了解決方案。除了期待access-tokentoken-typeuid之外,我的API還希望標頭中的client ID。這個client ID在sign_in請求響應中發送。