7

我遇到的问题是我正在使用门卫资源所有者凭据流来验证来自 iOS 应用程序的用户。我的项目有两个独立的用户模型(我们称它们为用户和管理员)。我的代码如下所示:

resource_owner_from_credentials do |routes|
  user = User.find_for_database_authentication(:email => params[:username])
  user if user && user.valid_password?(params[:password])
end

它可以工作,但我该如何检查管理员呢?换句话说,我不知道登录的人是用户还是管理员 - 我如何检查两者?

4

2 回答 2

10

Doorkeeper为此目的提供了范围(参见https://github.com/doorkeeper-gem/doorkeeper/wiki/Using-Scopes

因此,在您的 doorkeeper.rb 文件中,您可以执行以下操作:

resource_owner_from_credentials do |routes|
  if params[:scope].present?
    case params[:scope]
      when "user"
        u = User.find_for_database_authentication(:email => params[:email])
      when "admin"
        u = Admin.find_for_database_authentication(:email => params[:email])
    end
  else 
    #default auth
    u = User.find_for_database_authentication(:email => params[:email])
  end
  u if u && u.valid_password?(params[:password])
end  

然后为了验证您的资源(例如管理员),您可以发出这样的请求:

POST $HOST/oauth/token
{
  email: john@doe.com
  password: johndoe
  grant_type: password
  scope: admin
}
于 2014-10-23T20:40:06.643 回答
1

您可以通过传入一个额外的参数并根据该参数选择要进行身份验证的模型来做到这一点。这类似于 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 期望的范围界定的副作用。

于 2014-11-07T17:49:42.843 回答