簡體   English   中英

如何使用 devise-token_authenticable gem 訪問 current_user?

[英]How to access current_user with devise-token_authenticatable gem?

我的工作是使用一個小的項目devisedevise-token_authenticatableRails/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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM