Secure your Next.JS Application with Asgardeo and Next-Auth

Yathindra Kodithuwakku
Identity Beyond Borders
4 min readFeb 5, 2022

--

Get ready to add some security to your Next.JS app! In this tutorial, we’ll be implementing authentication with Asgardeo in just a few easy steps. The Asgardeo official React SDK isn’t compatible with server-side rendering (SSR), so we’ll be using NextAuth as our authentication library instead.

Let’s get started!

Asgardeo, the IDaaS that makes it a breeze to add login capabilities to your projects. You can create seamless login experiences in just minutes! Upgrade your authentication journey with Asgardeo.

In this article, we’ll be skipping the basics of authentication and focusing specifically on getting Asgardeo up and running in your Next.JS project. Let’s dive in!

First up, let’s set up our application in the Asgardeo platform.

1). Register an application from the Asgardeo console.

  1. Login to Asgardeo Console.
  2. Navigate to Develop tab and go to Applications.
  3. Click new Application and choose Standard based application.
  4. Then provide a name for the app and choose OpenIDConnect.
  5. In the application setting provide Authorized redirect URL as {YOUR_APP_DOMAIN}/api/auth/callback/asgardeo. E.g http://localhost:3000/api/auth/callback/asgardeo
  6. Also select code under Allowed grant types.
  7. The application domain put in the step 4 also need to be added under Allowed origins. E.g http://localhost:3000
  8. Then navigate to Protocol tab and get your Client ID and Client Secret.

2). Allow users to perform self registration.

  1. Navigate to Manage tab and go to Self Registration.
  2. Switch on Self Registration.

Great work setting up your Asgardeo application! Now let’s move on to the fun part: building our Next.JS app.

3). Create Next.Js Application

Create Next.JS application using the following command.

yarn create next-app

Then add next-auth dependency.

yarn add next-auth

Add the following environment variables in .env file

NEXTAUTH_URL=<Your Application domain e.g. http://localhost:3000>

SECRET=<Your Secret>

ASGARDEO_CLIENT_ID=<Client ID taken from Asgardeo console>

ASGARDEO_CLIENT_SECRET=<Client Secret taken from Asgardeo console>

ASGARDEO_SCOPES=openid email profile

ASGARDEO_SERVER_ORIGIN=<Server Origin>

To use Asgardeo for authentication in your Next.JS app, you’ll need to create a custom provider since it isn’t currently available in the NextAuth providers list. Just follow the steps and you’ll have it set up in no time!”

4). Create a custom Next-Auth Provider

To setup NextAuth in our Next.JS app, we’ll need to create a file named as […nextauth].js in the pages/api/auth path. This file will contain all of our NextAuth configurations, and any requests to /api/auth/ will be automatically handled by the library.

import NextAuth from "next-auth"

export default NextAuth({
providers: [
{
id: "asgardeo",
name: "Asgardeo",
type: "oauth",
clientId: process.env.ASGARDEO_CLIENT_ID,
clientSecret: process.env.ASGARDEO_CLIENT_SECRET,
wellKnown: `${process.env.ASGARDEO_SERVER_ORIGIN}/oauth2/token/.well-known/openid-configuration`,
authorization: {
params: { scope: process.env.ASGARDEO_SCOPES || "openid email profile" }
},
idToken: true,
checks: ["pkce", "state"],
profile(profile) {
return {
id: profile?.sub,
name: profile?.given_name,
email: profile?.email
}
},
httpOptions: {
timeout: 40000,
},
},
],
secret: process.env.SECRET,

session: {
strategy: "jwt",
},
})

To add authentication functionalities to the application, firstly, let’s add the next-auth session provider to _app.js as follows.

import { NavBar } from '../components/NavBar'
import { SessionProvider } from "next-auth/react"
import '../styles/globals.css'

function MyApp({ Component, pageProps }) {
return (
<SessionProvider session={pageProps?.session}>
<NavBar />
<Component {...pageProps} />
</SessionProvider>
)
}

export default MyApp;

In the index.js file, now we can retrieve the user session object under getServerSideProps.

As an additional note, with the NextAuth serverside session object you can check if a user’s session is active. If it’s not, you can redirect them to the sign-in page to authenticate. This is a handy way to ensure that only authenticated users have access to certain areas of your app.

export async function getServerSideProps(context) {
return {
props: {
session: await getSession(context),
},
}
}

Now you can access the session from your Next.JS page using.

const { data: session, status } = useSession()

This session object can be used to access user information.

Also to sign in, can invoke the following function.

signIn("asgardeo", { callbackUrl: "/" })

Cheers..!! You have successfully implemented authentication in your next.js application. Time to celebrate! 🎉

Hope you have gained some knowledge on developing secured nextjs application using NextAuth and Asgardeo.

You can find below the Next.js sample application with discussed functionalities.

Secure your web apps using Asgardeo — Click here to start for free

Great work building your Next.JS app with authentication!

If you want to deploy it to Vercel, you can do so with just a few clicks. Just make sure to add the necessary environment variables in the Vercel dashboard and you’ll be good to go.

Appreciate you taking the time to check this out! If you liked what you read, hit the clap button and give me a follow to stay in the loop. 😎

Happy coding!

--

--