【问题标题】:Accessing token authenticated user in Rails API在 Rails API 中访问令牌认证用户
【发布时间】:2023-03-10 02:59:02
【问题描述】:

我目前有一个设置了令牌身份验证的 API。我有一个父类 ApiController,我的其他 API 控制器继承自它包含以下内容:

class ApiController < ApplicationController
  protect_from_forgery with: :null_session

  protected 
    def authenticate
      authenticate_token || render_unauthorized
    end

    def authenticate_token
      authenticate_with_http_token do |token, options|
        User.find_by(auth_token: token)
      end
    end

    def render_unauthorized
      self.headers['WWW-Authenticate'] = 'Token realm="Users"'
      render json: 'Bad credentials', status: 401
    end
end

在我的 API 控制器中,我只是设置了before_action :authenticate,以确保它是来自具有auth_token 的用户的有效请求。

我有时需要发出请求的用户,例如,当关注一个用户时,我需要让发出请求的用户关注另一个用户,看看我有什么我该如何设置它,所以在我的控制器中我可以访问发出请求的用户吗?

【问题讨论】:

    标签: ruby-on-rails api authentication token


    【解决方案1】:

    您可以在authenticate_token 方法中设置一个可由控制器访问的实例变量。就这样

     @current_user = User.find_by(auth_token: token)
    

    然后,例如,您定义为“关注”用户的 Controller::Action 可以使用@current_user。

     def follow()     
       @current_user.follow (another_user)
     end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多