【发布时间】: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