我正在尝试在grape-api-rails应用程序中使用design配置令牌生成。由于我有当前版本的设计,令牌生成已被禁用。我有几个问题。首先,当我向会话控制器提交用户名和密码时,它会给我一个错误,即"ensure_authentication_token":
undefined method `ensure_authentication_token!' for #<User:0x007f880cca9090>
这很奇怪,因为正如您在下面看到的,我在用户模型中定义了它,当我在rails控制台中手动创建用户时,它可以正常工作。
这是范围问题吗?或者为什么会发生这种情况?
用户型号:
class User < ActiveRecord::Base
before_save :ensure_authentication_token
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
def ensure_authentication_token
if authentication_token.blank?
self.authentication_token = generate_authentication_token
end
end
private
def generate_authentication_token
loop do
token = Devise.friendly_token
break token unless User.where(authentication_token: token).first
end
end
end
会话葡萄API控制器:
module API
module V1
class Sessions < Grape::API
include API::V1::Defaults
resource :sessions do
params do
requires :email, type: String, desc: "Email"
requires :password, type: String, desc: "Password"
end
post do
email = params[:email]
password = params[:password]
if email.nil? or password.nil?
error!({error_code: 404, error_message: "Invalid Email or Password."},401)
return
end
user = User.where(email: email.downcase).first
if user.nil?
error!({error_code: 404, error_message: "Invalid Email or Password."},401)
return
end
if !user.valid_password?(password)
error!({error_code: 404, error_message: "Invalid Email or Password."},401)
return
else
user.ensure_authentication_token!
user.save
{status: 'ok', token: user.authentication_token}.to_json
end
end
end
end
end
end
第二个问题是,当我关注这个博客时,它说我需要在基本api控制器的defaults.rb中添加以下身份验证检查。当我添加"做之前"部分时,即使我输入了正确的凭据,我也会收到拒绝访问错误,而且它甚至不会继续到我上面提到的会话控制器的其他部分。
before do
error!("401 Unauthorized, 401") unless authenticated
end
helpers do
def warden
env['warden']
end
def authenticated
return true if warden.authenticated?
params[:access_token] && @user = User.find_by_authentication_token(params[:access_token])
end
def current_user
warden.user || @user
end
end
谢谢你的帮助!
编辑:菲利普完全正确地认为,其中一个问题是由于ensure_authentication_token的爆炸版本与非爆炸版本造成的。正在删除!控制器解决了这个问题。另一个问题实际上是添加了我的"before-do"循环。
这非常接近工作,我可以在我的api中发送和接收令牌,但当它连接到ember时,它会抱怨缺少csrf令牌,尽管我在应用程序中设置了"protect_from_forgery with::null_session"。rb
在用户模型中,您定义了一个名为ensure_authentication_token
的方法。
在会话控制器中,您调用一个名为ensure_authentication_token!
的方法。
这些方法不同:为什么在Ruby方法中使用感叹号?
这会阻止您生成身份验证令牌,这可能解释了"401未经授权,401"错误的原因。