问题
Currently I have an access token api with username, password and grant_type as password in my request in rails using doorkeeper. But I need to make client_id and secret as mandatory fields in the request. How can I do that. Can anyone please help to make this.
In my doorkeeper.rb config file,
resource_owner_from_credentials do |routes|
#client = OAuth2::Client.new(request.params[:client_id], request.params[:client_secret], site: "http://localhost:3000/")
#auth_url = client.auth_code.authorize_url(:redirect_uri => "urn:ietf:wg:oauth:2.0:oob")
request.params[:user] = {:email => request.params[:username], :password => request.params[:password]}
request.env["devise.allow_params_authentication"] = true
request.env["warden"].authenticate!(:scope => :user)
end
I want to authenticate using user credentials and also want to make client_id and secret a required field. I want to show a message if the client_id and secret is missing.
回答1:
Inside the block, you can check the presence of params[:client_id]
and params[:client_secret]
, and do the necessary check to make sure that they are valid :)
resource_owner_from_credentials do |routes|
raise Doorkeeper::Errors::DoorkeeperError if params[:client_id].blank? || params[:client_secret].blank?
dk_app = Doorkeeper::Application.find_by(uid: params[:client_id])
raise Doorkeeper::Errors::DoorkeeperError if dk_app.blank? || dk_app.secret != params[:client_secret]
## here do some checking that the client_id and secret are valid
request.params[:user] = {:email => request.params[:username], :password => request.params[:password]}
request.env["devise.allow_params_authentication"] = true
request.env["warden"].authenticate!(:scope => :user)
end
if you need to change the error message to a custom one you can refer to this issue
回答2:
You can add this code to your doorkeeper.rb config file,
# Doorkeeper patch: Always require a client on resource owner password flow
Doorkeeper::OAuth::PasswordAccessTokenRequest.class_eval do
private
def validate_client
!!client
end
end
It makes sure that the client application is always required for the password flow. Then the client_id and the client_secret are validated internally by Doorkeeper. If they are invalid the default error message from Doorkeeper for that case is provided.
Monkey patching is always ugly, but since Doorkeeper doesn't really allow to customize natively this behaviour I think it's a valid solution for now.
来源:https://stackoverflow.com/questions/28535306/make-client-id-and-secret-mandatory-in-access-token-request-with-grant-type-pass