Overview
Some situations might require an API to be called from a rule either to update a user or other functionality.
Rules run after every successful authentication. This is something to keep in mind when deciding how to sequence rules and whether to do this on every authentication or conditionally. Long API calls will make authenticating take more time. It is recommended that more expensive rules (like an API call) are run last. For example, if returning an unauthorized error if the user hasn’t verified their email, do that before calling the API.
Solution
To do this, configure the rule to make an API call. Add Machine 2 Machine (M2M) authorization between the rule and the target API, just like you would between any two non-interactive clients, protecting the transaction with Auth0.
- Register the API through the Dashboard or the Management API.
- In the Dashboard, navigate to APIs > Create API.
- Set up the API, register the permissions, and manage the M2M applications.
- Register an application for the rule.
- Navigate to Applications > Create Application.
- Select the M2M application and create.
- Click on the APIs tab in the application settings and toggle the API that was just created to Authorized.
- Create the rule.
- Navigate to Rules > Create Rule > </> Empty Rule.
- Request an access token designated for the API that was registered and make whatever API call is needed.
- Add the client ID and client secret to the global configuration object in the settings section.
Here is an example:
function (user, context, callback) {
const axios = require('axios@0.19.2');
//Request the access token
const options = { method: 'POST',
url: `https://${auth0.domain}/oauth/token`,
headers: { 'content-type': 'application/json' },
timeout: 5000,
data: `{"client_id":"${configuration.RULE_APP_CLIENT_ID}","client_secret":"${configuration.RULE_APP_CLIENT_SECRET}","audience":"https://test-api","grant_type":"client_credentials"}` };
axios(options)
.then( res => {
const access_token = res.data.access_token;
//Call your API
console.log(res.data);
})
.catch( err => {
console.log(err);
});
return callback(null, user, context);
}
NOTE: Axios 0.19.2 is used in the example, the latest version available in rules. Make sure to check what Node.js modules are available in rules. 311