[英]How to access current_user with devise-token_authenticatable gem?
我的工作是使用一個小的項目devise
和devise-token_authenticatable
在Rails/GraphQL/Apollo/React
設置。 項目是使用webpacker
設置的,因此前端和后端都來自同一個域。 登錄、注冊、注銷都由前端(React)處理。 我還需要指出這不僅僅是一個 API 應用程序。
看來,服務器沒有設置current_user
或正確的 cookie,我收到了網絡錯誤。
Heroku 日志顯示以下錯誤:
NoMethodError (undefined method `authentication_token' for #<User:0x000055ca6c0e4c50>)
這是否意味着它正在 nil 類上嘗試“authentication_token”方法?
同時它在控制台中顯示此錯誤:
Network error: Unexpected token < in JSON at position 0 (I have no idea what this is)
在我的登錄組件的登錄突變中,我在成功登錄后將用戶的 authentication_token 存儲在本地存儲中,在我的 Apollo 設置中,我從存儲中檢索它並將其附加到每個請求。 但是 Chrome 開發工具的網絡選項卡顯示在響應標頭中登錄后,我沒有獲得設計設置的 cookie。 我對這一切都很陌生,所以不確定這是問題還是其他問題。 PS:我沒有使用設計會話,因為登錄是在最后處理的。 我有devise_for: users, skip: :sessions
在我的路線中。
代碼片段:
非常感謝任何幫助。 預先感謝您的幫助。
更新:問題已修復:(另請參閱下面的答案以獲取更多信息)
通過在application_controller.rb
添加current_user
私有方法修復了問題。
這是代碼...
def current_user
token = request.headers["Authorization"].to_s
User.find_for_database_authentication(authentication_token: token)
end
Marko Kacanski 是對的,我應該詳細說明我的發現以及我如何修復它。 :-(
我錯誤地假設當 gem devise-token_authenticatable
在標頭中檢測到authentication_token
時,它會自動發送current_user
是錯誤的。 至少在我設置項目的方式中,我沒有按預期獲得current_user
,而是獲得了一個 nil 對象。
所以......我在application_controller.rb
創建了一個current_user
私有方法,它解決了這個問題。
這是代碼...
def current_user
token = request.headers["Authorization"].to_s
User.find_for_database_authentication(authentication_token: token)
end
修復了問題。 它與 GraphQl/Apollo 代碼無關。 謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.