How to Authenticate a Next.js app with Okta

nefejames - Aug 16 '22 - - Dev Community

Ensuring that only authenticated users have access to specific parts of an application is an important aspect of web development.

In this article, we will learn how to authenticate a Next.js application using Appwrite’s Okta OAuth2 provider.

The source code is also available on GitHub.

Prerequisites

To get the most out of this project, the following are required:

  • Basic understanding of React and Next.js

  • Docker installation

  • An Appwrite instance; check out this article on how to set up an instance

  • An Okta developer account (sign up here)

Getting Started

Create a Next.js project by running the command below in our terminal:



npx create-next-app okta-auth-app


Enter fullscreen mode Exit fullscreen mode

Next, navigate into the project directory.



cd okta-auth-app


Enter fullscreen mode Exit fullscreen mode

Then, run the command below to start the application:



 npm run dev


Enter fullscreen mode Exit fullscreen mode

Installing Appwrite

Appwrite is an open-source, end-to-end development platform that allows developers to build applications faster. Run the command below to install it:



npm i appwrite


Enter fullscreen mode Exit fullscreen mode

Creating a New Appwrite Project

To create a new project, start up the Appwrite instance on your machine and navigate to the specified hostname and port http://localhost:80. Next, we need to log in to our account or create an account if we don’t have one.

Signup/login page

On the console, click the Create Project button, give the project a name, and then click Create.

Create project

Enter project name

The project dashboard will appear on the console. Next, click on the Settings tab and copy the Project ID and API Endpoint.

Appwrite Project ID and API Endpoint

Creating an Appwrite Instance in the Next.js App

Create a utils.js file in the root of the application and in there, paste the code below:



import { Appwrite } from "appwrite";
const appwrite = new Appwrite();
appwrite
  .setEndpoint("http://localhost/v1")
  .setProject("your-project-id");
export default appwrite;


Enter fullscreen mode Exit fullscreen mode

We used the Appwrite Project ID and API Endpoint to set up the instance in our application.

Activating Okta Auth Method on Appwrite

Navigate to the Users menu, select the Settings tab, and enable the Okta OAuth2 provider:

Okta providers

Upon enabling the Okta provider, we will be required to fill in the App ID and App Secret. We will fill them in shortly.

Copy Appwrite’s callback URI below, as we will need it to configure the Okta authentication later.

Okta's OAuth settings

Setting up an Okta Application

We need to set up a new integration on our Okta account. Go to the Applications page on the sidebar menu and click the Create App Integration button.

Okta developer account page

Select OIDC - OpenID Connect as the Sign-in method and Web Application as the Application type.

Creating a new Okta app integration

We need to configure the new app integration to work with Appwrite. Add the callback URI we copied earlier as one of the Sign-in redirect URIs, then save the application.

New app integration

We also need to copy the Okta domain, Client ID, and Client Secret and paste them into our Appwrite configuration. Then, click Update.

Okta Client ID and Secret

Update Okta provider on Appwrite

Integrating Appwrite Authentication into Next.js

The application will contain two pages; a page to log in and another page to show logged-in user details.

Creating the login page Update the index.js file inside the pages folder with the snippet below:



import Head from "next/head";
import { Button, Center } from "@chakra-ui/react";
import appwrite from "utils";

export default function Home() {

  const loginWithOkta = async () => {
    try {
      await appwrite.account.createOAuth2Session(
        "okta",
        "http://localhost:3000/user"
      );
    } catch (error) {
      throw error;
    }
  };

  return (
    <Center>
      <Button onClick={loginWithOkta}>Login with Okta</Button>
    </Center>
  );
}


Enter fullscreen mode Exit fullscreen mode

Here, we did the following:

  • Imported the required dependencies

  • Created a loginWithOkta asynchronous function that uses the Appwrite dk we initialized earlier to authenticate using Okta as the provider and http://localhost:3000/user as the URL it redirects to when the authentication is successful; we will create the user page in the next section

  • Passed the loginWithOkta function to the button’s onClick handler

Creating the User Page
Create a user.js file in the pages directory and update it with the snippet below:



import { Button, Center, Text, Heading, Stack } from "@chakra-ui/react";
import { useEffect, useState } from "react";
import { useRouter } from "next/router";
import appwrite from "utils";

export default function User() {
  const [loggedInUser, setLoggedInUser] = useState(null);
  const router = useRouter();

  const getLoggedInUser = async () => {
    const data = (await appwrite) && appwrite.account.get();
    data
      .then((res) => setLoggedInUser(res))
      .catch((err) => {
        router.push("/");
        console.log(err);
      });
  };

  useEffect(() => {
    getLoggedInUser();
  }, []);

  const logOut = async () => {
    await appwrite.account.deleteSession("current");
    alert("logout successful");
    router.push("/");
  };

  return (
    loggedInUser && (
      <Center>
        <Stack>
          <Heading>You logged-in successfully</Heading>
          <Text>User: {loggedInUser.name}</Text>
          <p>Email: {loggedInUser.email}</p>
          <Button onClick={logOut} mt={20}>
            Logout
          </Button>
        </Stack>
      </Center>
    )
  );
}


```javascript

Here, we did the following:

-   Imported the required dependencies

-   Created state and route variables to manage logged-in user sessions and route accordingly

-   Created a `getLoggedInUser` function to get the logged-in user session and re-route to the login page if the session is empty and also called the function upon page load using the `useEffect` hook

-   Created a `logOut` function to log the user out and passed it to the button’s `onClick` handler

With that, we have successfully authenticated a Next.js app application with Okta.

![Demo](https://paper-attachments.dropbox.com/s_1638054D4FB2873BD3F938D25C75E763BFF13000BF29E067143C7C912818FACD_1656544770916_ezgif.com-gif-maker2.gif)

Conclusion
----------

This post discussed how to authenticate a Next.js application using Appwrite’s Okta OAuth2 provider.

Resources
---------

These resources might be helpful:

-   [Set up Appwrite instance locally](https://dev.to/hackmamba/create-a-local-appwrite-instance-in-3-steps-19n9?utm_source=hackmamba&utm_medium=hackmamba) 

-   [Appwrite OAuth2 documentation](https://appwrite.io/docs/client/account?sdk=web-default#accountCreateOAuth2Session)

-   [Appwrite - Getting Started for Web](https://appwrite.io/docs/getting-started-for-web)


Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .