Friday, 13 May, 2022 UTC


Summary

Introduction
The security of your customers’ data is essential and goes beyond just the application. Alerting customers when their account information changes, such as a username or password, is a great way to show customers you're looking out for them. You can pair Twilio SendGrid with Auth0 Actions to email users when their passwords change to build another layer of trust.
This blog post will walk you through sending a password change email using SendGrid’s Mail Send endpoint with Auth0 Actions.
Prerequisites
  • A free Twilio SendGrid Account – Sign up here.
  • A free Auth0 Account – Sign up here
  • An application in your Auth0 account. If you don't have one, you can use one of the Auth0 Quickstarts with a sample application.
Set up SendGrid
Before sending emails using SendGrid, you'll need to verify your Sender Identity and generate your API key. Verify the Sender Identity to confirm that you own the email address you're sending from. The Sender Identity is the 'from' email address users see when they receive your emails. The API key protects sensitive areas of your SendGrid account from unauthorized access.

Verify your Sender Identity with SendGrid

While logged into SendGrid, scroll down on the left-hand side menu and click Settings > Sender Authentication.
You'll have two options on the Sender Authentication page: Domain Authentication and Single Sender Verification. Single Sender Verification is a quick way to start sending emails during development.
On the Sender Authentication page click the Verify a Single Sender button.
For production, it’s recommended to use Domain Authentication to verify your Sender Identity.
Fill out the Create a Sender form that appears on the right side of the page. When all of the required fields are filled, click Create. SendGrid will send an email to the “from” email address that was provided to verify that email address. This email should have the subject line Please Verify Your Single Sender. After opening the message, click Verify Single Sender. You'll be redirected back to SendGrid and able to use that email address to send messages from Auth0.
The next step is to create an API key that will be stored as a secret with Auth0.

Generate SendGrid API Key

You can create your API key by going to the left side menu and clicking Settings > API Keys.
On the API Key page, click Create API Key in the upper right corner. Type in a name for your API key on the Create API Key form, select Full Access under API Key Permissions, then click Create & View. This page displays your API key. It’s recommended that you copy this and save it in a secure location. Lastly, click Done.
SendGrid is now configured to send emails. Now head over to Auth0 to create an Auth0 Action that uses SendGrid to send a password change email.
What are Auth0 Actions?
Auth0 Actions are serverless functions written in Node.js. Code is written in Auth0's in-browser code editor which is stored and runs on an infrastructure owned and maintained by Auth0. There is also Auth0 Actions marketplace where you can add custom integrations without writing any code. You can also add npm packages, store secrets, and even test Actions before deploying them. Once deployed, you can add the Action to run after various trigger points within the authorization flow.
Today you'll learn Actions with the Post Change Password flow.

Create an Auth0 Action

To create an Action, login to Auth0, navigate to your dashboard and on the left side menu, click Actions > Library. You're on the Library page, which shows your Actions.
The Library page has two tabs. The first tab, Installed, is for any third-party Actions installed from the Actions marketplace. The second tab, Custom, is for any Actions you created. To create your first Action, click the Build Custom button near the upper right corner of the page.
Clicking Build Custom will bring up the Create Action modal. Here is where you'll give your Action a name, select which trigger you want to use to activate the Action, and the Node version. For this example:
  1. Fill in "SendGrid API" in the Name field.
  2. Select Post Change Password from Trigger drop-down.
  3. Keep the Runtime on the recommended Node 16.
After those three fields are filled out, click Create.
Clicking Create will bring up the Actions in-browser code editor. Here, you can write the code to send the email using the SendGrid API.

Write Auth0 Actions Code with SendGrid Mail Send Endpoint

Before diving headfirst into writing code, take a tour of the code editor.
In the upper right corner, there are three buttons: Version History, Save Draft, and Deploy:
  • Version History is where you can store your Actions and can revert to previous versions.
  • Save Draft is for saving your code and coming back to work on it later.
  • Deploy is for when your code is complete and tested, and you're ready to use it.
On the left side of the editor, you’ll see three symbols
  • The first one is the "play" symbol, where you'll test your Action before you deploy it.
  • Below is a key symbol where you'll store your secrets, like an API key.
  • The last symbol is a box; this is where you'll install npm packages.
The first steps you’ll take are installing an npm package and storing a secret.
To send the password change email, you'll use Twilio SendGrid's Mail Send endpoint to send an email by HTTP request. Axios will let you make HTTP requests from node.js. Install axios from npm to get started.
Click the "box" icon on the left side of the editor. When the Dependencies menu pops out, click Add Dependency.
In the Add Dependency modal, enter "axios" in the Name field. You can leave Version alone as it defaults to the latest published version. The last step is to click Create. Now [email protected] will show up on the Dependencies menu.
Next, you’re going to add your SendGrid API key. Click the key icon to bring up the Secrets menu. Click Add Secret to bring up the Add Secret modal.
For this example, enter SENDGRID_API_KEY in the Key field. Then, paste in the API key you created on the SendGrid dashboard into the Value field, then click Create.
Close the Secrets menu by clicking the X. Now you can get started writing code in the code editor (Yay!).
Replace the code in the editor with the following:
const axios = require("axios"); exports.onExecutePostChangePassword = async (event) => { try { axios.post('https://api.sendgrid.com/v3/mail/send', { personalizations: [{ to: [{ email: event.user.email }] }], // Replace this email address for the verified sender in your SendGrid account from: { email: '[email protected]' }, subject: 'Your password was changed', content: [{ type: 'text/plain', value: 'The password for your ' + event.connection.name + ' account ' + event.user.email + ' was recently changed.' }] }, { headers: { 'Authorization': 'Bearer ' + event.secrets.SENDGRID_API_KEY }, } ); } catch (err) { console.log(`Error sending email to ${event.user.email}:`, err.message) } }; 
The first line of code, const axios = require("axios");, includes the axios npm package in your project.
Inside the exports.onExecutePostChangePassword function, you run an axios POST request with two parameters: the SendGrid Mail Send endpoint URL and an object containing the properties you want to send to the server.
Inside the object that is part of the axios request, you defined Personalizations, which is an array of objects with metadata about the email. In this example, the personalizations array defines the metadata for to, from, subject, and content.
You also sent an Authorization Header with your request that included your API key to authenticate this request. You have a headers property whose value is an object with Authorization and its property and Bearer plus your API key as its value.
Now click the Save Draft button, so that your code is safe. Notice how you're getting the following data:
  • The email address in the to field
  • The application's name for the value property
  • Your API key in the header property.
You access these values using the Actions event object. The event object contains different information depending on which Actions trigger you're using.
Before deploying your Action, it's a good idea to test it before adding it to your application.

Test Auth0 Actions

You can test your code to ensure it runs correctly without leaving the editor page. Click the "play" icon to bring up the Test menu. This menu also shows you all the properties you can access with the event object. Click the Run at the bottom of the menu.
You'll get a Test Results pop-up that will tell you if there are any errors and give you some stats like the runtime and network duration. Make sure the errors section is empty and click Deploy.
With a tested and deployed Action, the next step is to add the Action to the Post Change Password flow so it will be live to your users.

Add Action to ​​Post Change Password Flow

Actions have a drag-and-drop editor to add the code you just wrote to your application. You can add multiple Actions to a flow to have a truly customized experience.
On the left side menu, click Actions > Flows.
You're now on the Choose Flow page. This page lists all of the available flows you can attach to Actions. For today's application, choose the Post Change Password.
Take a tour of the drag-and-drop flow editor. In the center of the screen, you have two points, Start, which is the trigger (the password change), and Complete. You can drag the Actions you want to run between these two points. On the right, there is the Add Action section. There are two tabs in the Add Action menu. The Installed tab is for Actions you've added from the marketplace. The Custom tab is for the custom Actions you’ve written.
Click the Custom tab to see the SendGrid API Action you just created. Now click and drag your Action between the Start and Complete points and click Apply.
Just like that your app is now configured to alert users by email when their password is changed. The final step is to test the password change in your actual application.

Test Password Change in Live Application

The Action is now live for your users to try on your application. Test out a password change to experience it from the user's perspective. Run your application locally and click your Login button.
This brings up the Auth0 login page for users to enter their email and password. Ensure you already have an account with this application – If you don’t sign-up from this page and sign-out. Luckily, you "forgot" your password just in time to test out this new feature. Proceed to click Forgot Password?. Enter your email address on this page to send the password reset instructions and click Continue.
Check your email for a link to reset your password. Click the link and you'll be taken to the Auth0 Change Your Password page. Enter a strong password and re-enter to confirm it and click Reset password. You'll see a Password Changed! page that will send an email alerting you of the change! Congrats!
Conclusion
You just experienced the power of combining the SendGrid Mail Send endpoint with Auth0 Actions to keep your users up to date with changes on their accounts. Whenever users change their password, they will receive an email alerting them. You didn't have to write a lot of custom code or reconfigure your application.
Dive ever deeper into using SendGrid and Node.js by building an email newsletter application. Contact forms are all over the web; here, you'll learn how to build a content form with SendGrid and Node.
Will Johnson is a Developer Advocate at Auth0. You can find Will teaching on egghead.io, speaking at conferences or interacting with the developer community on Twitter.