Resolving "invalid_grant" error

Well, this is a perfect "works on my machine" kinda scenario.

While working on D-AR, sometimes, we'd start getting "invalid_grant" errors from our Api. I believe, to effectively solve an error, you have to first find a pattern. In this case, nothing was coming to our head. So, suddenly, one thing strikes - "it just happened after we deployed a new version". First, we thought - "is a change in oAuth settings are doing anything?". We tried a few options but no effect. At last, it was concluded that restarting app pool was the culprit.

But, what is causing it? Quick thought - oAuth must be keeping tokens in memory. We're close.

oAuth lib uses an in-memory machine key to encrypt and decrypt tokens. So, when you restart your app pool, it generates a new machine key, and it fails to decrypt your token that was encrypted using earlier machine key.

So, what's the Solution?

Simple - Use the same machine key.

If your app is hosted on multiple machines then you have to copy the same machine key to every machine or store it in a central storage system like Azure key vault.

Solution steps -

1. Locate your site's machine key like below

2. Once you double click on it, it will open a new screen like below -

3. Here is the problem. So, uncheck "Automatically generate at runtime" checkbox for both - validation and decryption key. Click 'Generate Keys' button on the right and then 'Apply'.

Remember to remove that "IsolateApps" text before generating keys. Otherwise, you know it - an error will happen.

These settings have solved the "invalid_grant" error for us.

Happy many, many and many more successful deployments now :-)


References -

1. - gave us a good starting point

2. - another validation of our thought

3. - Good read about auth server

4. - one more validation of our hypothesis

5. - Google search

6. - Encrypting web.config sections

7. - helped us with changing machine key in IIS 

8. - data protection for core

Add comment