您可以通过传入一个额外的参数并根据该参数选择要进行身份验证的模型来做到这一点。这类似于 gdonato 的回答,但门卫中的范围更好地用于管理向经过身份验证的应用程序授予哪些权限(即“授予此应用程序代表您读取 X 和写入 Y 的权限”)。
这是我正在使用的
resource_owner_from_credentials do |routes|
if params[:user_type].present?
case params[:user_type]
when 'user'
u = User.find_for_database_authentication(email: params[:email])
when 'employer'
u = Employer.find_for_database_authentication(email: params[:email])
when 'admin'
u = Administrator.find_for_database_authentication(email: params[:email])
end
end # I don't want a default auth user_type, so no 'else' block for me
user if user && user.valid_password?(params[:password])
end
请注意,如果您要使用范围而不是门卫尚未用于其他用途的参数来执行此操作,则必须配置范围,例如:
# These are found in doorkeeper.rb, but they're commented by default.
# You would use whatever scopes you're wanting to check
default_scopes :public
optional_scopes :write, :update
使用范围作为参数来区分 User 和 Admin 可能会在不调整 doorkeeper.rb 中的 default_scopes 或 optional_scopes 的情况下工作,但只是作为 doorkeeper 期望的范围界定的副作用。