Sign in users programmatically with Auth0 using the Resource Owner Password Flow

Cover image
Photo by Travis Saylor

Recently I wanted to automate the process of acquiring bearer tokens from Auth0 to use when end-to-end testing an api I was developing. I used the Resource Owner Password Flow to achieve that.

Note: I recommend not using this approach in a production environment since it might make some attack protection features to fail.

To get going, navigate to the settings of the application you like to use by navigating to Applications -> Applications and click on it. Open the Settings tab and grab the domain, clientId and clientSecret.

Scroll to the bottom of the same page and expand the Advanced Settings section. Open the Grant Types tab and enable Password. Don't forget to click on the Save Changes button.

Navigate to your Tenant Settings page by clicking Settings in the menu. Under the General tab, find the section API Authorization Settings. Set the field Default Directory to whatever connection you like to use as a default. For Example Username-Password-Authentication.

Using NodeJS, you can use the following script to get a bearer token.

const fetch = require('node-fetch')
const { URLSearchParams } = require('url')

;(async function main() {
  const response = await fetch('[DOMAIN]', {
    method: 'POST',
    body: new URLSearchParams({
      "grant_type": "password",
      "username": process.env.AUTH0_USER,
      "password": process.env.AUTH0_PASSWORD,
      "scope": "openid",
      "client_id": "[CLIENT_ID]",
      "client_secret": "[CLIENT_SECRET]",
      "audience": "[AUDIENCE]"
    })
  })

  const { access_token, id_token, scope, expires_in, token_type, ...rest } = await response.json()
  
  if(!response.ok){
    console.error(rest)
    process.exit(-1)
  }

  console.log('ACCESS TOKEN', access_token)
})()

Invoke the script as follows

$ AUTH0_USER=[USER_NAME] AUTH0_PASSWORD=[PASSWORD] node auth.js

Eventual errors that might occur:

  • Error: "Grant type 'password' not allowed for the client."
    Solution: You have forgot to enable the password grant. Enable password grant.
  • Error: "Authorization server not configured with default connection."
    Solution: You have forgot to configure the Default Directory in your Tenant Settings. Configure the Default Directory.
  • Error: "Connection is disabled (client_id: [CLIENT_ID] - connection: [DEFAULT DIRECTORY])
    Solution: Your application is not enabled to use the connection. Navigate to your connection under Authentication and go to the tab Applications and enable your application.

Happy testing!