Login succeeds, but can't exchange code for token

Since I’ve seen other people having issues with this, I wanted to share my experience with configuring authentication in a new environment for the first time. I’m setting up a new regular web app (Rails 6.0 RC1) and can authenticate successfully in my local dev environment. I’m also deploying to a staging environment on Heroku, and created a new tenant with the same settings (except for allowed callback/logout URLs).

In the staging tenant, I can login successfully with the Database connection via the “try” button from the dashboard. From the app, I was able to authenticate successfully as well, but when the omniauth-auth0 gem tried to complete the process and get a token from the returned code (POST https://<tenant-domain>.auth0.com/oauth/token), it failed with:

omniauth: (auth0) Authentication failure! invalid_credentials: OAuth2::Error, access_denied: Unauthorized

I enabled debugging by setting OAUTH_DEBUG=true, and so the logs show an HTTP 401 Unauthorized response to the POST /oauth/token request. I tried:

  • Destroying and recreating the tenant from scratch
  • Verifying that the client ID and secret are set correctly
  • Rotating the secret

to no avail.

Root cause: I eventually realized that the problem was in my Rails credentials.yml.enc config file. I was trying to use ERB to set the client secret from an env var on Heroku:

auth0_client_secret: <%= ENV['AUTH0_CLIENT_SECRET'] %>

But it seems that doesn’t work in the new credentials file the way it does in the (older) config/secrets.yml mechanism and other Rails YAML config files.

Solution: I updated my initializer to take the client secret from either the environment (for Heroku deployments) or from credentials.yml.enc (for local dev), i.e.:

Rails.application.config.middleware.use OmniAuth::Builder do
    ENV['AUTH0_CLIENT_ID'] || Rails.application.credentials.auth0_client_id!,
    ENV['AUTH0_DOMAIN'] || Rails.application.credentials.auth0_domain!,
    callback_path: '/auth/oauth2/callback',
    authorize_params: {
      scope: 'openid profile'

Hope this helps someone else!

1 Like

Hi @krbullock,

Welcome to the Auth0 Community!

This is awesome feedback, and what a developer community is all about! It great to have first hand experience with frustrating problems, and even better to have a solution! Thanks for taking the time out of your day to share your problem AND solution. We really do appreciate it! :+1:

If you run into any more issues don’t hesitate to ask!

Warm Regards,

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.