Skip to main content

Implement Auth0 With Your Node.js App

 

What Is Auth0?

Auth0 is a third-party tool that provide services for authentication and authorization. It provides the building blocks for authentication and authorization, allowing you to secure your applications without having to become security experts. You can integrate Auth0 into any Node.js app.

To implement Auth0 with Node.js, first you need to create an account on Auth0. Then, log in.

Step 1: Get the Auth0 Application Keys

Now we need to do some configuration on Auth0, so let’s do it.
When you signed up for Auth0, a new application was created for you — or you could have created a new one. We need the following information:

  • Domain key
  • Client ID key
  • Client-secret key
Image for post
Snapshot: Auth0 dashboard

Now get the application keys and save them somewhere:
Go to the Applications > Defaut App > Settings.

Image for post
Snapshot: Copy the keys

Copy the Domain, Client ID, and Client Secret. They’ll be used in our Node app.

Step 2: Configure the Callback URL in Your Auth0 App

callback URL is an URL in your application where Auth0 redirects the user after the authentication.

To add this, go to Applications > Defaut App > Settings, and
in the Allowed Callback URLs box, enter http://localhost:3000/callback.

Image for post
Snapshot: Allowed Callback URLs box

Step 3: Configure the Logout URL in Your Auth0 App

logout URL is an URL in your application that Auth0 can return to after the user has been logged out of the authorization server. This is specified in the returnTo query parameter.

To add this, go to Applications > Defaut App > Settings, and
in the Allowed Logout URLs box, enter http://localhost:3000.

Image for post
Snapshot: Allowed Logout URLs box

Step 4: Now Click on Save Changes

You need to save the changes you’ve done right now.

Image for post
Snapshot: Save the changes

Step 5: Now Let’s Create a Node.js Server

To do this, create a folder called auth0, and create a file named app.js. Paste the following code inside app.js:

var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var flash = require('connect-flash');
const app = express();
app.get('/test',(req,res,next)=>{
res.send({message:"Server is on"});
})
// View engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(flash());
// Handle auth failure error messages
app.use(function (req, res, next) {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.send({message: err.message,error: {} });
});
app.listen(8080,()=>{
console.log("Server is runnig on port 8080");
});
module.exports = app;

Now open terminal, and go to the app.js location. Run the command :

npm install express cookie-parser connect-flash morgan

After successfully running the above command, run the app.js file using the below command:

node app.js

And you can see the output as:

Image for post
Snapshot: Node app.js

Also, you can test your server by hitting the below API in your browser:

Image for post
Snapshot: Server is on

If you can see the above message, it means your server is running.

Now Let’s Configure Our Node.js App With Auth0

1: Create the .env file

Create the .env file in the root of your app, and paste the following code. Replace the actual values of YOUR_CLIENT_IDYOUR_DOMAIN, and YOUR_CLIENT_SECRET.

.env:

AUTH0_CLIENT_ID=YOUR_CLIENT_ID
AUTH0_DOMAIN=YOUR_DOMAIN
AUTH0_CLIENT_SECRET=YOUR_CLIENT_SECRET

2. Install the dependencies to support Auth0

We need to install the dependencies. To do so, run the following command:

npm install passport passport-auth0 express-session dotenv pug --save
Image for post
Snapshot: npm install passport passport-auth0 express-session dotenv pug --save

3. Add the following code into your app.js file

var session = require('express-session');

// config express-session
var sess = {
secret: 'CHANGE THIS TO A RANDOM SECRET',
cookie: {},
resave: false,
saveUninitialized: true
};

if (app.get('env') === 'production') {
// Use secure cookies in production (requires SSL/TLS)
sess.cookie.secure = true;

// Uncomment the line below if your application is behind a proxy (like on Heroku)
// or if you're encountering the error message:
// "Unable to verify authorization request state"
// app.set('trust proxy', 1);
}

app.use(session(sess));

4. Add the code for Passport and the application settings

// Load environment variables from .env
var dotenv = require('dotenv');
dotenv.config();

// Load Passport
var passport = require('passport');
var Auth0Strategy = require('passport-auth0');

// 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:
process.env.AUTH0_CALLBACK_URL || '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);
}
);

passport.use(strategy);
app.use(passport.initialize());
app.use(passport.session());

Please make sure these last two commands are in your code after the application of the Express middleware (app.use(session(sess)).

Now, your final app.js file after the above code addition will look like this:

var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var dotenv = require('dotenv');
var passport = require('passport');
var Auth0Strategy = require('passport-auth0');
var flash = require('connect-flash');
dotenv.config();// 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:
process.env.AUTH0_CALLBACK_URL || 'http://localhost:3000/callback'
},
function (accessToken, refreshToken, extraParams, profile, done) {
return done(null, profile);
});
passport.use(strategy);// You can use this section to keep a smaller payload
passport.serializeUser(function (user, done) {
done(null, user);
});
passport.deserializeUser(function (user, done) {
done(null, user);
});
const app = express();
app.get('/test', (req, res, next) => {
res.send({ message: "Server is on" });
})
// View engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(cookieParser());
// config express-session
var sess = {
secret: 'CHANGE THIS SECRET',
cookie: {},
resave: false,
saveUninitialized: true
};
app.use(session(sess));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
app.use(flash());
app.use(function (err, req, res, next) {
res.status(err.status || 500);|
res.send({message: err.message,error: err});
});
app.listen(8080, () => {
console.log("Server is runnig on port 8080");
});
module.exports = app;

Step 6: Now We Need to Create the API Login

Now we need to create the API’s: /login. Now we’ll create a folder called routes at the root location with the following files:

  • routes/auth.js to handle authentication
  • routes/index.js to serve the home page

Let's create a file called auth.js inside the routes folder and paste the following code:

auth.js:

// routes/auth.js
var express = require('express');
var router = express.Router();
var passport = require('passport');
var dotenv = require('dotenv');
dotenv.config();
// Perform the login, after login Auth0 will redirect to callbackrouter.get('/login', passport.authenticate('auth0', {
scope: 'openid email profile'}), function (req, res) {
res.redirect('/');
});
module.exports = router;

Step 7: Create an Index Route to Serve the Homepage:

To do this, create a file called index.js inside the routes folder, and paste the following code:

// routes/index.js
var express = require('express');
var router = express.Router();
/* GET home page. */router.get('/', function (req, res, next) {
res.render('layout', { title: 'Auth0 Webapp sample Nodejs' });|
});
module.exports = router;

Step 8: Add Routes Into Your app.js File

Paste the following code inside your app.js file:

var authRouter = require('./routes/auth');
var indexRouter = require('./routes/index');


app.use('/', authRouter);
app.use('/', indexRouter);

Now your final app.js file after the above code addition will look like this:

var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var dotenv = require('dotenv');
var passport = require('passport');
var Auth0Strategy = require('passport-auth0');
var flash = require('connect-flash');
var authRouter = require('./routes/auth');
var indexRouter = require('./routes/index');
dotenv.config();
// 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:process.env.AUTH0_CALLBACK_URL || 'http://localhost:3000/callback'
},
function (accessToken, refreshToken, extraParams, profile, done) {
return done(null, profile);
});
passport.use(strategy);// You can use this section to keep a smaller payload
passport.serializeUser(function (user, done) {
done(null, user);
});
passport.deserializeUser(function (user, done) {
done(null, user);
});
const app = express();
app.get('/test', (req, res, next) => {
res.send({ message: "Server is on" });|
})
// View engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(cookieParser());
// config express-session
var sess = {
secret: 'CHANGE THIS SECRET',
cookie: {},
resave: false,
saveUninitialized: true
};
app.use(session(sess));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
app.use(flash());
app.use('/', authRouter);
app.use('/', indexRouter);
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.send({message: err.message,error: err});
});
app.listen(8080, () => {
console.log("Server is runnig on port 8080");
});
module.exports = app;

Step 9: Create Views for the Home Page:

To do this, create a folder called views at the root location, and create a file named layout.pug. Paste the following code:

doctype html
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
link(rel='stylesheet', href='https://www.w3schools.com/w3css/4/w3.css')
link(rel='shortcut icon', href='//cdn2.auth0.com/styleguide/latest/lib/logos/img/favicon.png')

body
nav.w3-bar.w3-border.w3-light-grey( role="navigation" )
.w3-bar-item.w3-text-grey Auth0 - NodeJS
a(href="/").w3-bar-item.w3-button Home
a(id="qsLoginBtn" href="/login").w3-bar-item.w3-button Log In
block content
h4 Welcome in Auth0 Implementation: Shubham Verma blogs

Let’s see the snapshot:

Image for post
Snapshot: layout.pug

Step 10: Run the App, and See the Result:

Now that you’ve done your coding, it’s time to run the app.js file using the following command:

node app.js

You can see the output is:

Image for post
Snapshot: Node app.js

Now open the browser, and enter the URL localhost:8080. And see the page:

Image for post
Snapshot: localhost:8080

Now click Log In, and see the magic. You can see the Auth0 login page displayed.

Image for post
Snapshot: Auth0 login page

Let’s see the combined result in the following GIF:

Image for post
Snapshot: Complete journey of Auth0

Congratulations. Now we’ve implemented Auth0 with Node.js.

To understand more about Node.js, read this

Comments

Popular posts from this blog

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functions, scales, axis and shape ge

JavaScript new features in ES2019(ES10)

The 2019 edition of the ECMAScript specification has many new features. Among them, I will summarize the ones that seem most useful to me. First, you can run these examples in  node.js ≥12 . To Install Node.js 12 on Ubuntu-Debian-Mint you can do the following: $sudo apt update $sudo apt -y upgrade $sudo apt update $sudo apt -y install curl dirmngr apt-transport-https lsb-release ca-certificates $curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash - $sudo apt -y install nodejs Or, in  Chrome Version ≥72,  you can try those features in the developer console(Alt +j). Array.prototype.flat && Array.prototype. flatMap The  flat()  method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. let array1 = ['a','b', [1, 2, 3]]; let array2 = array1.flat(); //['a', 'b', 1, 2, 3] We should also note that the method excludes gaps or empty elements in the array: let array1

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component