Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Getting authentication failure error #169

Open
manoj2411 opened this issue Jan 16, 2015 · 39 comments
Open

Getting authentication failure error #169

manoj2411 opened this issue Jan 16, 2015 · 39 comments

Comments

@manoj2411
Copy link

Hi,

I can understand the obvious reason of this can be wrong client_id or client_secret or user credentials but the same credentials are working with databasedotcom gem.

When I tried it with restforce like

client = Restforce.new :client_id => "***G9ZL0ppGP5UrDYpAXumi8nwstjCLYvheoFNrg3PyY6BEy4p98VyOKsrAUEqKRjC4cUPHz07yMttAGc9***", :client_secret => "5713668283413776***", host: 'test.salesforce.com', :username => "manoj***@gmail.com", :password => "manoj***Uwy4XwMytmAQZvpJb7aub***", :security_token => "Uwy4XwMytmAQZvpJb7aub***"

client.query('select Id, Name from User').first

I got error Restforce::AuthenticationError: invalid_grant: authentication failure

And when I tried it with databasedotcom like

client = Databasedotcom::Client.new :client_id => "***G9ZL0ppGP5UrDYpAXumi8nwstjCLYvheoFNrg3PyY6BEy4p98VyOKsrAUEqKRjC4cUPHz07yMttAGc9***", :client_secret => "5713668283413776***"
client.host = 'test.salesforce.com'
client.authenticate :username => "manoj***@gmail.com", :password => "manoj***Uwy4XwMytmAQZvpJb7aub***" 

And it just worked fine. Please correct me if I am missing something.

@pxlpnk
Copy link

pxlpnk commented Feb 11, 2015

I have the same behaviour. The weird part is the sometimes it works, and sometimes I get the invalid_grant error. It is not really possible to reproduce this as it seems to be random.

It happens if I use the same client object over and over again but also if I instantiate a fresh client for every call.

@jay-o
Copy link

jay-o commented Apr 1, 2015

Bump

I'm having the same issues over here. Our issue is only in our development and testing environments interacting with SFDC Sandbox. We'll be able to successfully connect, then in subsequent tries/calls it fails.

# First try success
[1] pry(main)> client = Restforce.new
=> #<Restforce::Data::Client @options={:a.....
2] pry(main)> client.authenticate!
=> {"id"=>"https://test.salesforc.......

# Subsequent tries fail
client = Restforce.new
=> #<Restforce::Data::Client @opt.....
[2] pry(main)> client.authenticate!
Restforce::AuthenticationError: invalid_grant: authentication failure

Any solutions out there?

@imranansari
Copy link

Dang! this seems like a bad one, occurring it Production now.
Would love to hear if any one found a workaround.

@jmagoon
Copy link

jmagoon commented Jun 9, 2015

Had this error today and found something that fixed it

Going to connected apps in salesforce and changing 'permitted users' from 'Admin approved users are pre-authorized' to 'All users may self-authorize' immediately fixed it for me.

@dlamichhane
Copy link

When you have to establish a Salesforce session several times then it is usually advantageous to use a singleton implementation.

@cworsley4
Copy link

+1. Same issue.

@DavidVII
Copy link

👍 looks like this is just a SF issue.

@yuuki1224
Copy link

Restforce::AuthenticationError: invalid_grant: authentication failure
I've also solved this problem by relaxing the IP restriction on admin view.
See: this post on SalesForce forum

And also this page is helpful to solve authentication failure.
https://help.salesforce.com/apex/HTViewSolution?id=000212208&language=en_US

@tmac
Copy link

tmac commented Mar 22, 2016

For me the restforce documentation was wrong. I had to remove the security token option for it to work. So instead of:

client = Restforce.new :username => 'foo',
  :password       => 'bar',
  :security_token => 'security token',
  :client_id      => 'client_id',
  :client_secret  => 'client_secret'

it's

client = Restforce.new :username => 'foo',
  :password       => 'bar',
  :client_id      => 'client_id',
  :client_secret  => 'client_secret'

@timrogers
Copy link
Collaborator

@tmac Interesting! In the documentation it says that now you have to append the security token to the password - but we're definitely providing them separately. I'll leave the documentation for now until we find out some more.

@JSFernandes
Copy link

I just spent a couple of hours dealing with this issue and I can confirm that I was unable to authenticate until I removed the SALESFORCE_SECURITY_TOKEN from my environment variables and appended the token to the password set in SALESFORCE_PASSWORD

@timrogers
Copy link
Collaborator

Strange. I'm definitely not doing that with out Salesforce instance - perhaps it's a different version or something like that.

Would you like to add a note to README.md? Thanks for taking the time to debug!

Sent from my iPhone

On 21 Apr 2016, at 18:14, João Fernandes notifications@github.com wrote:

I just spent a couple of hours dealing with this issue and I can confirm that I was unable to authenticate until I removed the SALESFORCE_SECURITY_TOKEN from my environment variables and appended the token to the password set in SALESFORCE_PASSWORD


You are receiving this because you commented.
Reply to this email directly or view it on GitHub

@JSFernandes
Copy link

Will do, but can you confirm the API version that you're using? I'm using version 36 and didn't try any other version. Perhaps we can pinpoint which versions require this approach and be specific about that in the README.

@tmac
Copy link

tmac commented Apr 21, 2016

I can confirm this with both the default version (28 I think?) and 32 which I'm currently using.

@tmac
Copy link

tmac commented Apr 21, 2016

It's probably worth noting that so far I've only tested against our sandbox. Is it possibly different in production?

@JSFernandes
Copy link

After some more testing I discovered that this was partially my fault. Here's what happened:

  • Initially I was testing with a typo in my username
  • I didn't notice the typo, thought it was related to the security token and thus appended the token to the password, as salesforce suggests
  • I was still unable to authenticate, eventually noticed the typo in the username and corrected it. Was still unable to authenticate
  • Removed the SALESFORCE_SECURITY_TOKEN from the environment variables, was able to authenticate
  • Commented here, started doing some testing
  • Realised that by removing the token from the password and keeping the SALESFORCE_SECURITY_TOKEN variable allowed me to authenticate (which was what I had at first, albeit with a typo in the username)

Terribly sorry about the confusion.

tl;dr: you can either set the security token through the environment variable or by appending it to the password. However, don't do both or authentication will fail.

@timrogers
Copy link
Collaborator

🎉🎉🎉 Great work!

Sent from my iPhone

On 21 Apr 2016, at 18:58, João Fernandes notifications@github.com wrote:

After some more testing I discovered that this was partially my fault. Here's what happened:

Initially I was testing with a typo in my username
I didn't notice the typo, thought it was related to the security token and thus appended the token to the password, as salesforce suggests
I was still unable to authenticate, eventually noticed the typo in the username and corrected it. Was still unable to authenticate
Removed the SALESFORCE_SECURITY_TOKEN from the environment variables, was able to authenticate
Commented here, started doing some testing
Realised that by removing the token from the password and keeping the SALESFORCE_SECURITY_TOKEN variable allowed me to authenticate (which was what I had at first, albeit with a typo in the username)
Terribly sorry about the confusion.

tl;dr: you can either set the security token through the environment variable or by appending it to the password. However, don't do both or authentication will fail.


You are receiving this because you commented.
Reply to this email directly or view it on GitHub

@jonathan-upstart
Copy link

jonathan-upstart commented Apr 23, 2016

Update 1: only when connecting to SFDC from Heroku can I reproduce these sporadic errors; when I connect to login.salesforce.com using my local machine and authenticate using the Restforce gem, the authentication succeeds 100% of the time. Not sure why but will continue to investigate.

Update 2: I can successfully authenticate via CURL dozens of times without error, both from my local machine and from a Heroku bash shell running on my Heroku dyno: curl -v https://login.salesforce.com -d "grant_type=password&username=xxx&password=xxx&client_id=xxx&client_secret=xxx".

I'm having this problem as well. It's sporadic, but about 4-10% of the time I get authentication errors:

count = 0

100.times do
  begin
    client = Restforce.new(
      host: "login.salesforce.com",
      api_version: "36.0",
      username: username,
      password: password,
      security_token: security_token,
      client_id: consumer_key,
      client_secret: consumer_secret)

    client.authenticate!
  rescue Restforce::AuthenticationError
    count += 1
  end
end

count # varies from ~4 to 12

I tried removing the security_token field and appending the security token to password, but I still got intermittent authentication failures. I also tried increasing the version to 36, with no luck. Any advice?

@bitops
Copy link

bitops commented Jul 28, 2016

Same issue. Tried all of the fixes in here on Tuesday and it worked. Now it's Thursday and it's not working again. Really weird.

@lubieniebieski
Copy link

worked for me: I had to "unlock" the user manually - I went to user/edit and there was an "unlock" button available. 1 click and no more errors:)

@lashdav
Copy link

lashdav commented Aug 17, 2016

I'm experiencing a similar issue -- successfully authenticate via CURL, but when I try to use this gem I am not getting an access token. Followed all the tips out there in order to get the CURL command to work correctly (relaxed IP restrictions, all users may self authorize). This was very helpful: http://www.calvinfroedge.com/salesforce-how-to-generate-api-credentials/

With restforce (using the username/pw auth flow) I have tried concatenating my security token to my password, keeping the security token in addition to un/pw/client id/client secret, and removing security token altogether. Still unable to successfuly auth with restforce.

Any suggestions? This seems to be the most relevant issue thread with recent activity.

@timrogers
Copy link
Collaborator

Hi David! It might be worth getting in touch with Salesforce - it's
presumably something account specific that is breaking this as it's still
working fine for us in production (and others using the gem).

It might be worth following through the authentication logic (starting in
https://github.com/ejholmes/restforce/blob/master/lib/restforce/concerns/authentication.rb,
and going through some middlewares) to try to see what's going on, too.

On Wed, Aug 17, 2016 at 10:57 PM David Lasher notifications@github.com
wrote:

I'm experiencing a similar issue -- successfully authenticate via CURL,
but when I try to use this gem I am not getting an access token. Followed
all the tips out there in order to get the CURL command to work correctly
(relaxed IP restrictions, all users may self authorize).

With restforce (using the username/pw auth flow) I have tried
concatenating my security token to my password, keeping the security token
in addition to un/pw/client id/client secret, and removing security token
altogether. Still unable to successfuly auth with restforce.

Any suggestions? This seems to be the most relevant issue thread with
recent activity.


You are receiving this because you commented.
Reply to this email directly, view it on GitHub
#169 (comment),
or mute the thread
https://github.com/notifications/unsubscribe-auth/AAHFpmY9hbleS6e4zx2ZkzqgTxpageDWks5qg4O_gaJpZM4DTTW1
.

@adamthedeveloper
Copy link

What ever happened with this? It's now 2018 and this is still happening to me (new salesforce user). Why is it so hard to have clarity around how to connect and have the right auth sauce?

@timrogers
Copy link
Collaborator

It's difficult for me to say - although I maintain the gem, I've never experienced the problem myself, and we've never got a clear view of exactly how people have fixed it when they have done. Have you experimented with some of the solutions in this thread?

@sicktastic
Copy link
Collaborator

@adamthedeveloper can you share how you are authenticating so we can help? What error are you getting?

@hoenth
Copy link

hoenth commented Jan 10, 2018

As a note, I received the invalid_grant message doing this:

client = Restforce.new(username: 'foo',
                   password: 'bar',
                   security_token: 'security token',
                   client_id: 'client_id',
                   client_secret: 'client_secret',
                   api_version: '41.0')

But connected successfully using this and NOT appending the security token to the PW:

client = Restforce.new(username: 'foo',
                   password: 'bar',
                   client_id: 'client_id',
                   client_secret: 'client_secret',
                   api_version: '41.0')

@adamthedeveloper
Copy link

@hoenth I am seeing the exact opposite of you. I have to pass in the username, password, security_token, client_id and client_secret or I get invalid_grant.

So strange that different combos work for different people. What's even more frustrating is that the authority, Salesforce themselves, don't spell out exactly what settings are needed to auth correctly.

One thing I will say is that our api_version is 26.0. We've just recently signed up to use salesforce and the responses I get back from salesforce include this:

#<Restforce::Data::Client @options={:api_version=>"26.0", 

Should I be setting the api_version like you are in your example? What caveats are there to forcing the api version?

@hoenth
Copy link

hoenth commented Jan 11, 2018

@adamthedeveloper How do you know your API version is 26? 26.0 may be the default in RestForce if no other api version is supplied. 41 is the current version. At least, it is the version that is listed when I build the wsdl for our instance. If you go to Setup | Build | Develop | API | Generate Partner WSDL, you should see the version that you are using.

@adamthedeveloper
Copy link

@hoenth My clue that 26 is the version simply came from the response back within the options attribute when I instantiate the client:

#<Restforce::Data::Client @options={:api_version=>"26.0", 

I'll take a look at that WSDL page you suggested to see what it says. I am currently not specifying the version when I instantiate the client. It prints out as api_version 26.0 - hence, I assume that is the version salesforce is defaulting to - as you suspect.

@adamthedeveloper
Copy link

Hmmm.....when I instantiate a client, will it eventually timeout or something? I'm using a singleton in my rails app. When I open a console and try to run a query, it works fine. I never get auth failures. I'm wondering if setting up the client as a singleton upon app initialization is the problem. Does the client timeout?

@adamthedeveloper
Copy link

Ok, a little more to show you. I'm getting this error:

Restforce::UnauthorizedError: Connection prefix not set

Again, this only happens on occasion and I'm not sure why. Any help anyone can offer is most welcome.

Thanks- Adam

@pre
Copy link

pre commented May 7, 2018

I was also investigating this Restforce::AuthenticationError: invalid_grant: authentication failure problem. For me, the issue eventually was that I was using the username/password flow, and I didn't notice that changing the user account's password also caused the security token being reset.

The new security token got emailed to an email address that I didn't follow. I found this thing out when I redid the setup from scratch - then I noticed there were previously sent "security token was reset" emails that had gone unnoticed.

Providing both the security token and password works for me:

client = Restforce.new(username: ENV.fetch('SALESFORCE_USERNAME'),
                       password: ENV.fetch('SALESFORCE_PASSWORD'),
                       security_token: ENV.fetch('SALESFORCE_SECURITY_TOKEN'),
                       client_id: ENV.fetch('SALESFORCE_CONSUMER_KEY'),
                       client_secret: ENV.fetch('SALESFORCE_CONSUMER_SECRET'),
                       api_version: ENV.fetch('SALESFORCE_API_VERSION'))

# Methods for checking whether the connection works
client.authenticate!
client.describe

@chadwilken
Copy link

So I was also hitting this and the key was removing the security_token and removing the ENV var since the lib auto detects the var

@peeyush-ad2games
Copy link

peeyush-ad2games commented Jul 30, 2018

This error is coming randomly for us as well, we are not using security_token stuff but the OAuth #and still getting this error:-

Configuration sample:-

Restforce.configure do |config|
  config.host           = ENV.fetch('SF_HOST')
  config.instance_url   = ENV.fetch('SF_INSTANCE_URL')
  config.refresh_token  = ENV.fetch('SF_REFRESH_TOKEN')
  config.client_id      = ENV.fetch('SF_CLIENT_ID')
  config.client_secret  = ENV.fetch('SF_CLIENT_SECRET')
  config.api_version    = ENV.fetch('SF_API_VERSION')
  config.authentication_callback = proc { |x| Rails.logger.debug x.to_s }
end
  • API version:- 41.
  • All users may self-authorize.
  • Remove security_token

@peeyush-ad2games
Copy link

peeyush-ad2games commented Jul 31, 2018

Tried to dig down a bit and tried creating HTTP request myself with the creds and when we are getting errors in Restforce a normal curl request also starts to fail, so I think it's more of a salesforce issue.

@E-Xor
Copy link

E-Xor commented Jul 22, 2020

Had the same issue as the OP. I was testing in sandbox and needed to specify host (test.saleforce.com) in Restforce.new(), that fixed it for me.

@mikel
Copy link

mikel commented Dec 23, 2021

Hey there @timrogers I think I might have found what this is, or at least why I am getting invalid_grant errors.

The system I am building sends messages one at a time as they come in, this all works perfectly, then suddenly, after a busy period I just start getting invalid_grants.

As this sounded like a limit issue to me (working -> high traffic -> not working) I investigated, and sure enough, I was doing more than 3600 requests in an hour and hitting the Salesforce 3600 logins per hour limit (we use username / password in our request). -> https://help.salesforce.com/s/articleView?id=000312767&type=1

Looking around, I can't find a way to tell RestForce to use the same SessionId as a previous request, does RestForce support this?

As a second note, I'm getting "invalid_grant" from Salesforce as the error, not too many logins or some other helpful message :)

After a bit of thinking, I tried implementing a simple thread based cache on the RestForce client for my background job, and this seems to be working...

So for others who might be hitting this, instead of something like this:

class SendToSalesforceService

  attr_reader :client

  def initialize
    @client ||= Restforce.new
    ...
  end

  def execute!
    client.upsert(...)
  end

Which will initialize a new restforce client every time you send something to salesforce... try something like this:

class SendToSalesforceService

  def initialize
    ...
  end

  def client
    Thread.current[:restforce_client] ||= Restforce.new
  end

  def execute!
    client.upsert(...)
  end

Which will set up one RestForce client per thread running. As we have about 40-50 sidekiq jobs running sometimes to clear out thousands of entries we are sending to Salesforce, it seems this handles it with only 1 login per sidekiq worker instead of one per entry sent.

@IanVaughan
Copy link

IanVaughan commented May 23, 2023

@ lubieniebieski many many thanks!

worked for me: I had to "unlock" the user manually - I went to user/edit and there was an "unlock" button available. 1 click and no more errors:)

This was the trick!

Edit: SalesForce sends a email when the account is UNLOCKED:

Your Salesforce account is unlocked
Your Salesforce administrator removed the temporary lock on your account

But annoyingly doesn't send one to say its LOCKED!! 😞

@IanVaughan
Copy link

@mikel great idea, I am curious though... as each sidekiq job runs in its own process, do you really need the Thread.current code?
I am looking at just creating a client and assigning to a const within an initialiser... which seems to be working fine.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests