Friday, April 14, 2017

MERN Series Step 4 - Authentication with Auth0
They have a great intro video, watch it.

Our starter project already came with passport, so we'll just need to add passport-auth0 and express-session:
Yarn add passport-auth0 express-session auth0-lock

Looking at the architecture options, SPA+API looks like a natural fit to pursue:

You can also use the spa quickstart, that looks like it has some scripting that would be useful, I'll review that and compare in the next article.

You may also want to review JWTs as auth0 uses them, and they are beyond the scope of what I'm writing about in this series, I may get into some more detail later, but my focus with this series is not on JWTs.

First step, create a new account with the website name, then select Single Page App for the application type:

This will then present you with a sample project you can download (that will have your keys in it).  I've downloaded mine, it looks like the two files you'll need are in src/utils, with the rest of the code showing how to integrate into your app.  The .env file in the root contains your auth0 clientid and domain.  The code in src/views/Main/routes.js has examples of how to protect routes using react-router.  You can run the project itself using npm start, it just serves up a page with a login control that opens the auth0 login widget. 

Run it and try to log in and it will fail with CORS error.  Take a look at the logs for your auth0 Client (the application)

This means that we'll need to add http://localhost:3000 in order to have our sample auth0 app to connect.  Click on Clients, then on your app (mine is still "Default App") then settings, scroll down to "Allowed Origins (CORS)" and add http://localhost:3000, while you're there add http://localhost:3000/login to the "Allowed Callback URLs" area, as the sample app uses that for where auth0 sends data back to it.  Once you've done that you'll be able to login using one of the providers you've enabled (I enabled google and linked-in since this is a job board), and you should see a lovely landing page with welcoming you by name (nice!), with a logout button.

We'll take this sample app and incorporate it into our main application.  I'll be using a login widget instead of the full page layout of the auth0 sample, but beyond that we'll leave it the same.  We'll also use auth0 for authorization once we get to where we have multiple roles for our app.  Now, since we've logged into our app, you'll be able to see yourself as a user and view details.  Check it out under users:

No comments:

Post a Comment