Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Build and Authenticate a NodeJS App With JSON Web Tokens: Part III

DZone's Guide to

Build and Authenticate a NodeJS App With JSON Web Tokens: Part III

In the final part to this series, we will finish up with NodeJS authentication with Auth0.

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

Did you miss Parts I and II? Click the links to catch up!

Aside: NodeJS Authentication with Auth0

We set up a great foundation and our app is looking good. The final piece of the puzzle is to get authentication up and running, so users can log in and view the polls. We'll use Auth0 to accomplish this, but the Passport.js library has strategies for all major authentication frameworks and providers.

To get started, you'll need an Auth0 account. If you don't already have one, you can sign up for a free account here. Once you have an account, log in and navigate to the management dashboard and retrieve your Auth0 app specific keys. The three items you'll need specifically are: Client Id, Client Secret, and Domain.

Once you have these three items, go ahead and open up the .env file we created and create a variable for each of these. Your completed .env file should look like this:

AUTH0_CLIENT_ID=mRgDS6qIasvBPUrqGwlG37anUNbh2OPD
AUTH0_DOMAIN=YOUR-AUTH0-DOMAIN.auth0.com
AUTH0_CLIENT_SECRET=cVQNk5uUFc8qTYF0MW7rkT5tEoCgkXo9VS1BAXoR1zdYdPvNxR0f5bBcjD32dMS


Next, open up the app.js file. Here we will create our Auth0 authentication strategy. Check out the changes below. We are including the original code we've written so far, but have commented it out so you can see the changes we are adding.

// We have commented out the existing code so that you can see where to add the new code.

//DO NOT COMMENT OUT ANYTHING IN YOUR FILE

// var express = require('express');
// var path = require('path');
// var logger = require('morgan');
// var cookieParser = require('cookie-parser');
// var bodyParser = require('body-parser');
// var session = require('express-session');
// var dotenv = require('dotenv');
// Passport is the most popular Node Js authentication library
var passport = require('passport');
// We are including the Auth0 authentication strategy for Passport
var Auth0Strategy = require('passport-auth0');

// dotenv.load();

//var routes = require('./routes/index');

// This will configure Passport to use Auth0
var strategy = new Auth0Strategy({
    domain:       process.env.AUTH0_DOMAIN,
    clientID:     process.env.AUTH0_CLIENT_ID,
    clientSecret: process.env.AUTH0_CLIENT_SECRET,
    callbackURL:  'http://localhost:3000/callback'
  }, function(accessToken, refreshToken, extraParams, profile, done) {
    // accessToken is the token to call Auth0 API (not needed in the most cases)
    // extraParams.id_token has the JSON Web Token
    // profile has all the information from the user
    return done(null, profile);
  });

// Here we are adding the Auth0 Strategy to our passport framework
passport.use(strategy);

// The searlize and deserialize user methods will allow us to get the user data once they are logged in.
passport.serializeUser(function(user, done) {
  done(null, user);
});

passport.deserializeUser(function(user, done) {
  done(null, user);
});

// var app = express();

// app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'jade');

// app.use(logger('dev'));
// app.use(bodyParser.json());
// app.use(bodyParser.urlencoded({ extended: false }));
// app.use(cookieParser());
// app.use(session({
//  secret: 'shhhhhhhhh',
//  resave: true,
//  saveUninitialized: true
// }));
// We are also adding passport to our middleware flow
app.use(passport.initialize());
app.use(passport.session());
// app.use(express.static(path.join(__dirname, 'public')));

//app.use('/', routes);

// app.use(function(req, res, next) {
//  var err = new Error('Not Found');
//  err.status = 404;
//  next(err);
// });

// app.use(function(err, req, res, next) {
//  res.status(err.status || 500);
//  res.render('error', {
//    message: err.message,
//    error: err
//  });
// });

// app.listen(3000);


We have created an Auth0 authentication strategy and registered it with our application. We already have a login route, but we haven't implemented the UI, let's do that next. Open up the login.jade file and add the following code.

extends layout

block content  
  div(id="root" style="width: 280px; margin: 40px auto; padding: 10px;")

  script.
    var lock = new Auth0Lock('#{env.AUTH0_CLIENT_ID}', '#{env.AUTH0_DOMAIN}', { auth: {
          redirectUrl: '#{env.AUTH0_CALLBACK_URL}'
        , responseType: 'code'
        , params: {
          scope: 'openid name email picture'
        }
      }});
    lock.show();


Awesome Polls Login Page

We will make use of the Auth0 Lock widget for our authentication flow. Lock allows us to easily and effortlessly add a login box that can handle traditional username and password, social, and enterprise login methods as well as additional features like multifactor authentication all with the flip of a switch.

You may have noticed in the login.jade file, we are requiring some data from the env variable, but we are currently not passing those specific variables. Let's fix that. Open up the index.js page in the routes directory and let's make some final adjustments here as well.

// ...
var env = {
  AUTH0_CLIENT_ID: process.env.AUTH0_CLIENT_ID,
  AUTH0_DOMAIN: process.env.AUTH0_DOMAIN,
  AUTH0_CALLBACK_URL: 'http://localhost:3000/callback'
};

// ...

// We are also going to implement the callback route which will redirect the logged in user to the polls page if authentication succeeds.
router.get('/callback',
  passport.authenticate('auth0', { failureRedirect: '/' }),
  function(req, res) {
    res.redirect(req.session.returnTo || '/polls');
  });


We are now finally ready to test our application. Restart the server and head over to localhost:3000. You will be greeted with the homepage.

Click on the login button, and you will be sent to the /login page, where the Lock widget will be opened and you will be able to sign up or log in. Log in, or sign up if you haven't already created a test account, and you will be redirected to the /polls page.

On this page, you will be able to see the results of all 50 states. We got this data using the NodeJS request library and querying the Huffington Post API.

Finally, click on the logout link in the top right corner, and your user will be logged out and sent back to the homepage. Now that you are logged out, try accessing the /polls page and notice that since you are no longer logged in, you are redirected to the /login page.

Congrats! You just built an entire NodeJS app and added authentication to it.

Conclusion

NodeJS is a powerful language and framework for building modern applications. The community support through NPM is unrivaled and Auth0 can help secure your NodeJS apps with not just state of the art authentication, but enhanced features like multifactor auth, anomaly detection, enterprise federation, single sign-on (SSO), and more. Sign up today so you can focus on building features unique to your app. 

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:
node js ,app ,web dev ,json

Published at DZone with permission of Ado Kukic, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}