![](/img/trans.png)
[英]How can I get current_user by directly visiting an API url in rails app? I am using ng-auth-token and devise_token_auth for authentication
[英]How to get current_user in Rails using devise_token_auth?
我用devise_token_auth與設計一種身份驗證和登記。 一切順利:我可以登錄,使用api和web界面注銷。 但是我無法獲得current_user設計變量(nil)。
<% if current_user %>
<%= link_to "Edit profile", edit_user_registration_path(current_user.id) %> |
<%= link_to('Logout', destroy_user_session_path, :method => :delete) %>
<% else %>
<%= link_to "Register", new_user_registration_path %> |
<%= link_to('Login', new_user_session_path) %>
<% end %>
application_controller.rb
class ApplicationController < ActionController::Base
include DeviseTokenAuth::Concerns::SetUserByToken
protect_from_forgery with: :null_session, if: Proc.new { |c| c.request.format == 'application/json' }
end
我需要將此變量用作全局,例如,在application.html.erb中使用
嘗試這個
# app/controllers/test_controller.rb
class TestController < ApplicationController
before_action :authenticate_user!
def index
@user = current_user
end
end
注意before_action
。
authenticate_user!
負責設置current_user
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.