Authentication Made Easy with Auth0: Part 1
Authentication Made Easy with Auth0: Part 1
Through example, we will demonstrate how to use Auth0 to secure a Node.js (Express) API that is accessed by a single page application.
In the past, I have used Passport to secure my Node.js APIs; not a lot of code, but was a bit tricky to setup correctly the first time. This approach also gets significantly more complex as we add additional authentication requirements, e.g., social integrations, etc.
I have also used Firebase to build secured APIs; while super easy, Firebase is not suitable for many projects (not flexible enough)
Turns out that Auth0 combines the flexibility of Node.js APIs with the ease of securing it.
This series closely follows the Auth0 documentation on Architecture Scenarios > SPA + API
The final solution to this series is available for download.
Prerequisites
In order to follow along with this series, one needs:
Insecure API
Let us start by building our insecure (no authentication) API; starting with the Express
In a new folder, enter (and accept all defaults):
npm init
We then install Express:
npm install express
We then create our insecure API.
index.js
Observation:
- I can’t live without semi-colons; so I added them back in (smile)
- Changed port from 3000 to 8080 as we will be using 3000 later
Running our API and testing it with Postman:
node index.js
Insecure Application
Now that we have an API (assume it is still running), let us create an application (single page application) that consumes it. In another folder, we create:
index.html
Observations:
- It has been awhile, but this is old-school ES5
- As we still want to support IE11, we use both ES6 (Babel polyfill) and fetch (whatwg-fetch) polyfills
We can now run our application by entering and opening the browser to http://localhost:3000
npx http-server -p 3000 -c-1
Observations:
- The Node.js package, http-server, is a simple static web server; serving up our index.html file
- The -c option ensures that the application is never cached; helpful during development
- Pressing the Get button will generate JavaScript errors; visible in the console
- The first error is that the API and application are running on different ports (thus origins); we are getting a cross-origin resource sharing (CORS) error
- The second error (masked by the first) is that the response, the string hello world, is not valid JSON
Fixed Insecure API
We first address the CORS error. From the API folder we enter:
npm install cors
and update:
index.js
and to fix the response we also update:
index.js
With these changes, and restarting the API, we see that pressing the Get button outputs the expected response to the console.
Next Steps
Having setup both the insecure API and application, we can now get down to securing them in Authentication Made Easy with Auth0: Part 2 (writing in progress).