Article summary
I recently worked on a project using Auth0 for login where I needed to enforce password resets every 90 days. We needed to check the user’s last password reset date without making an additional request to the Auth0 management API. This information is available in the user metadata, but accessing it directly can be tricky. This is where Auth0 Actions come in handy.
Why Use Actions
Making an API call after a user is redirected back to the application would use an additional machine-to-machine token each time they log in. Using Auth0’s post-login action allows you to inject custom claims into the user’s id token before it is issued to the application, reducing the number of API calls needed to retrieve additional data.
Auth0 Actions
Actions offer a more flexible way to extend Auth0’s functionality. They are written in Node.js and make it easier to customize and enhance login flows in ways that aren’t available through the dashboard settings.
In this case of enforcing password resets, the application needed to access a user’s last_password_reset (note: this property is only available for authentication with database connections) property. In order to pass this information to the application this property needs to be added to the id token as a custom claim since OIDC standard claims don’t include a property representing last_password_reset.
Add a Custom Claim to an Action
- Select the “Post-Login” flow.
- Click “Add Action” and choose “Create Custom Action”.
- Give the action a name then press “Create”. You should see a JavaScript editor with an empty function. This is the entry point for post-login actions.
- Add this line to set a custom claim on the id token. When setting a custom claim, the key or namespace may need to be a “fully-qualified url” in order for it to be injected properly in the ID token. In this case set the claim name to be your application’s root url.
exports.onExecutePostLogin = async (event, api) => {
api.idToken.setCustomClaim('https://example.com/last_password_reset', event.user.last_password_reset);
};
- Save and deploy your action.
- Go back and select the post-login trigger and drag your custom action into the post-login flow.
Test Login Flow
Login to your application and inspect the idToken issued by Auth0. https://example.com/last_password_reset should be present as a custom claim with the last login date as the value. In this example, the last_password_reset value may be undefined if the user has never reset their password before.
With Auth0 Actions you can easily retrieve and include relevant user data in your id tokens. If you’ve never used Actions before, try experimenting with different triggers and claims and see what opportunities you may have to streamline your login flow.