Introduction
Single sign-on (SSO) is a mechanism that allows users to authenticate once and access multiple applications seamlessly without the need to enter their credentials repeatedly. Okta is a cloud-based identity management platform that provides SSO capabilities to web and mobile applications.
In this tutorial, you will learn how to integrate Okta SSO in a Node.js application step by step with code examples.
Prerequisites
Before you start, you need the following prerequisites:
A basic understanding of Node.js and Express.js
Node.js installed on your machine
A free Okta developer account
Step 1: Create a New Node.js Application
The first step is to create a new Node.js application. Open a terminal and run the following commands:
$ mkdir okta-sso-demo
$ cd okta-sso-demo
$ npm init -y
These commands create a new directory for your Node.js application, navigate to the directory, and initialize a new Node.js project with default settings.
Step 2: Install Dependencies
The next step is to install the dependencies required for your Node.js application. Run the following command:
$ npm install express express-session @okta/oidc-middleware ejs
These dependencies include:
express: A web framework for Node.js
express-session: A middleware for managing user sessions in Express.js
@okta/oidc-middleware: The Okta SDK for Node.js
ejs: A template engine for generating HTML pages
Step 3: Configure Okta Application
The next step is to create an Okta application and configure it for your Node.js application. Log in to your Okta developer account and follow these steps:
Click on “Applications” in the top menu bar and then click on “Add Application”.
Select “Web” as the platform and “Single Page App” as the sign-on method.
Enter a name for your application and click on “Next”.
Enter “http://localhost:3000/login/callback" as the “Login redirect URI” and “http://localhost:3000" as the “Logout redirect URI”. Click on “Done”.
Note the “Client ID” and “Client Secret” of your application. You will use these in your Node.js application.
Step 4: Implement Okta Configuration
The next step is to implement the Okta configuration in your Node.js application. Create a new file named “okta.js” in the root directory of your Node.js application and add the following code:
const session = require('express-session');
const OktaAuth = require('@okta/oidc-middleware').OktaAuth;
const oktaAuth = new OktaAuth({
clientId: 'YOUR_CLIENT_ID',
clientSecret: 'YOUR_CLIENT_SECRET',
issuer: 'https://YOUR_OKTA_DOMAIN.okta.com/oauth2/default',
appBaseUrl: 'http://localhost:3000',
scope: ['openid', 'email', 'profile'],
});
function oktaMiddleware(req, res, next) {
const { token } = req.session;
if (!token) {
return res.redirect('/login');
}
oktaAuth.token.verify(token)
.then((jwt) => {
req.userContext = { token, jwt };
next();
})
.catch(() => {
res.redirect('/login');
});
}
module.exports = {
oktaAuth,
oktaMiddleware,
};
This file initializes the OktaAuth object with the client ID, client secret, Okta issuer URL, application base URL, and required scopes. The oktaMiddleware function checks if the user has an access token in the session. If the user is not authenticated, the middleware redirects the user to the login page. If the user is authenticated, the middleware sets the user context with the access token and JWT and passes the control to the next middleware.
Step 5: Implement Login Route
The next step is to implement the login route in your Node.js application. Create a new file named “routes.js” in the root directory of your Node.js application and add the following code:
const { Router } = require('express');
const { oktaAuth } = require('./okta');
const router = Router();
router.get('/login', (req, res) => {
res.render('login', {
csrfToken: req.csrfToken(),
title: 'Login',
});
});
router.post('/login', oktaAuth.authenticate(), (req, res) => {
res.redirect('/');
});
router.get('/login/callback', oktaAuth.callback(), (req, res) => {
const { sessionToken } = req.userContext.tokens;
req.session.token = sessionToken;
res.redirect('/');
});
router.get('/logout', (req, res) => {
req.session.destroy();
req.logout();
res.redirect('/');
});
module.exports = router;
This file defines the login, callback, and logout routes for your Node.js application. The login route renders the login page with a CSRF token for security. The post request to the login route uses the Okta authentication middleware to authenticate the user with Okta. The callback route uses the Okta callback middleware to get the access token from Okta and store it in the user session. The logout route destroys the user session and logs out the user from Okta.
Step 6: Implement Home Route
The next step is to implement the home route in your Node.js application. Create a new file named “index.js” in the root directory of your Node.js application and add the following code:
const express = require('express');
const csrf = require('csurf');
const session = require('express-session');
const { oktaMiddleware } = require('./okta');
const routes = require('./routes');
const app = express();
const csrfProtection = csrf();
app.set('view engine', 'ejs');
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(session({
secret: 'SECRET_KEY',
resave: true,
saveUninitialized: false,
}));
app.use(csrfProtection);
app.use(oktaMiddleware);
app.use('/', routes);
app.listen(3000, () => {
console.log('Server started on port 3000');
});
This file initializes the Express.js app with the view engine, body-parser, session middleware, CSRF protection middleware, Okta middleware, and routes middleware. The CSRF middleware adds a CSRF token to all forms for security. The Okta middleware protects the routes that require authentication.
Step 7: Implement Login Page
The next step is to implement the login page for your Node.js application. Create a new file named “login. ejs” in the “views” directory of your Node.js application.
Conclusion
In this blog post, you learned how to integrate Okta SSO into your Node.js application step by step. You first created an Okta developer account and registered your application. Then, you installed the required dependencies and initialized the OktaAuth object in your Node.js application. You also implemented the login, callback, and logout routes and protected them with the Okta authentication middleware. Finally, you implemented the login page and home page for your Node.js application.
SSO is a powerful security mechanism that provides a seamless authentication experience for your users. By integrating Okta SSO into your Node.js application, you can provide a secure and easy-to-use authentication experience for your users.