Affinidi Login with NextJS

In this guide, learn how to enable passwordless login in your application with basic implementation of Affinidi Login.

The Affinidi Login can be integrated with any application that supports OIDC flow.

This lab uses NextJS and NextAuth.js as the framework to implement Affinidi Login.

Before you begin
  1. Set up Affinidi Vault Browser Extension. Follow the guide below if you haven’t set it up yet.
Set up Affinidi Vault
  1. Install the Affinidi Vault Browser Extension via Google Chrome store.

Affinidi Vault Affinidi Vault

  1. Click the Affinidi Vault Chrome extension found in the Extensions of the Chrome browser. Click START and provide a valid email address. If you have a backup of your Vault created previously, you can use RESTORE VAULT FROM BACKUP.
Set up Email Address in Affinidi Vault
  1. Enter the 6-digit verification code sent to the email address you provided in the previous step and click verify.
Enter Verification Code
  1. Secure your Vault by providing a secure passphrase. Use this passphrase to unlock your Vault.
Set up Passphrase on Affinidi Vault

Finally, you should see on the screen that you have successfully registered to the Affinidi Vault.

  1. Get the Redirect URI of your application for OIDC. This is the URI configured on your Login Configuration to receive the idToken after successful authorisation.

  2. Optionally, install the Affinidi CLI. Follow the guide below if it hasn’t been installed.

Set up Affinidi CLI
  1. Download and install NodeJS on your machine if you haven’t set it up yet.
  1. Install Affinidi CLI using Node Package Manager (npm).
    npm install -g @affinidi/cli
  1. Verify that the installation is successful.
affinidi --version

Download Application

You can clone this sample application using Next.js framework from our Github and start exploring how to integrate Affinidi Login to provide a passwordless login experience for your end-users.

Running the Application

  1. Suppose this is your first time downloading the sample application. Run the following command to install the dependencies.
npm install
  1. Create the .env file in the sample application by running the following command.
cp .env.example .env

If you open the sample application in a Code Editor, duplicate the .env.example and rename it .env.

  1. After installing the dependencies, run the application by running the command.
npm run dev

Running the application for the first time without configuring the .env file will throw an exception error. We will configure the required environment variables in the following steps of this guide.

You may refer to the included README.md file for more details.

Create Login Configuration

To create a Login Configuration, you can either use Affinidi CLI or  Affinidi Portal.

Expand the section below for your preferred method:

Name: My first config

Redirect URIs: http://localhost:3000/api/auth/callback/affinidi

Using Affinidi CLI
  1. Log in to Affinidi CLI by running:
affinidi start
  1. Once you have successfully logged in, create the Login Configuration by running:
affinidi login create-config \
--name='My Basic App' \
--redirect-uris='http://localhost:3000/api/auth/callback/affinidi'
  • --name is what you want your login configuration to be called.
  • --redirect-uris is the URL on your application where the user gets redirected after the successful authentication.

Sample response:

{
  "ari": "ari:identity:ap-southeast-1:687b8872-a618-dt63-8978-e72ac32daeb1:login_configuration/c4f74d936cd31bde1c1fd3c1050bb76s",
  "projectId": "687b8872-a618-4e52-8978-e72ac32daec2",
  "configurationId": "c4f74d936cd31bde1c1fd3c1050bb62d",
  "name": "My Basic App",
  "auth": {
    "clientId": "<AUTH.CLIENT_ID>",
    "clientSecret": "<AUTH.CLIENT_SECRET>",
    "issuer": "https://<PROJECT_ID>.apse1.login.affinidi.io"
  },
  "redirectUris": [
    "..."
  ],
  "clientMetadata": {
    "name": "My Basic App",
    "logo": "https://login.affinidi.com/default-client-logo.svg",
    "origin": "https://example.com"
  },
  "creationDate": "2023-08-11T06:26:37Z",
  "tokenEndpointAuthMethod": "client_secret_post"
}

Learn more on how to manage your Login Configurations using Affinidi CLI.

Using Affinidi Portal
Create new Login Configuratioin
  1. Go to  Affinidi Login under the Services section.

  2. Click on the Create Login Configuration and provide the required details.

  • Name is the string that describes your login configuration.
  • Redirect URIs is the URL on your application where the user gets redirected after the successful authentication.
  1. Click on create and confirm if all the details are correct.
Login Configuratation new client
  1. After confirming the details, another popup shows the Client ID and Client Secret for your Login Configuration. Copy the generated Client Credentials and use them to integrate with Affinidi Login.

  2. After copying the Client ID and Client Secret and closing the popup, you are redirected back to the Affinidi Login page.

Login Configuration uses the default Presentation Definition (presentationDefinition) and ID Token Mapping (idTokenMapping) that is used to request the user’s email address during the authentication flow.

Set up the Sample Application

Affinidi Login Sample

In this guide, learn how to integrate Affinidi Login using NextJS and NextAuth.js framework.

Configure .env file

Set the environment variables based on the auth credentials received from the Login Configuration created earlier:

{
  "auth": {
    "clientId": "<AUTH.CLIENT_ID>",
    "clientSecret": "<AUTH.CLIENT_SECRET>",
    "issuer": "https://<PROJECT_ID>.apse1.login.affinidi.io"
  }
}

Set the following fields in the .env file

PROVIDER_CLIENT_ID="<AUTH.CLIENT_ID>"
PROVIDER_CLIENT_SECRET="<AUTH.CLIENT_SECRET>"
PROVIDER_ISSUER="<AUTH.CLIENT_ISSUER>"

Configure NextAuth for Affinidi Login

Using the NextAuth.js library, configure the nextauth file to enable Affinidi Login as a login provider and set up the JWT and Session from the idToken sent by the Affinidi Login after the user successfully authenticates.

Add Affinidi Login as a Login Provider

In the code below, Affinidi Login is added as one of the Login Providers for NextAuth.js. The credentials generated by the Login Configuration are configured here and sent to the Affinidi Login service as part of the payload.

File path: src/lib/auth/auth-provider.ts


export const provider: Provider = {
  id: "affinidi",
  name: "Affinidi",
  clientId: providerClientId,
  clientSecret: providerClientSecret,
  type: "oauth",
  wellKnown: `${providerIssuer}/.well-known/openid-configuration`,
  authorization: {
    params: {
      prompt: "login",
      scope: "openid offline_access",
    },
  },
  client: {
    token_endpoint_auth_method: "client_secret_post",
  },
  idToken: true,
  profile(profile) {
    return {
      id: profile.sub,
      email: profile.custom?.find((i: any) => typeof i.email === "string")
        ?.email,
    };
  },
};
Generate JWT and Session from the idToken

In the code below, the JWT and the session are generated from the idToken received from Affinidi Login following successful user authentication.

File path: src/lib/auth/auth-options.ts


async jwt({ token, account, profile }) {
  const profileItems = (profile as any)?.[PROVIDER_ATTRIBUTES_KEY];
  if (profile && profileItems) {
    let userDID: string;
    let user: UserInfo = {};
    userDID = profileItems.find(
      (item: any) => typeof item.did === "string"
    )?.did;
    user.email = profileItems.find(
      (item: any) => typeof item.email === "string"
    )?.email;
    user.country = profileItems.find(
      (item: any) => typeof item.address === "object"
    )?.address?.country;
    token = {
      ...token,
      user,
      ...(userDID && { userId: userDID }),
    };
  }

  if (account) {
    token = {
      ...token,
      ...(account?.access_token && { accessToken: account.access_token }),
      ...(account?.id_token && { idToken: account.id_token }),
    };
  }

  return token;
},
// session is persisted as an HttpOnly cookie
async session({ session, token }) {
  return {
    ...session,
    ...(token.user && { user: { ...session.user, ...token.user } }),
    ...(token.accessToken && { accessToken: token.accessToken }),
    ...(token.idToken && { idToken: token.idToken }),
    ...(token.userId && { userId: token.userId }),
  };
},

The above files are then declared in the NextAuth file to register the login provider and the functions to handle the idToken response from Affinidi Login.

File path: src/pages/api/auth/[...nextauth].ts

import { authOptions } from "src/lib/auth/auth-options";
import NextAuth from "next-auth";

export default NextAuth(authOptions);

Additionally, you will notice in line 31 that we are parsing the country field. This optional process requires updating the Presentation Definition and ID Token Mapping of the Login Configuration to request the user profile from the Vault.

user.country = profileItems.find(
      (item: any) => typeof item.address === "object"
    )?.address?.country;

You can refer to this guide to learn how to update the Presentation Definition and ID Token Mapping.

Enable Affinidi Login

In the code below, we are enabling Affinidi Login into the Login page of the sample app and referencing the NextAuth provider configured earlier.

File path: src/lib/auth/client-login.ts

import { signIn } from "next-auth/react";
import { hostUrl } from "src/lib/variables";

export async function clientLogin() {
  await signIn("affinidi", { callbackUrl: hostUrl });
}

We include the above file in the SignIn page of the sample app and attach the event in the Login button to initiate the authentication flow.

<Button variant="primary" onClick={clientLogin}>
  <Image src={LogoAffinidi} alt="logo affinidi" />
  Affinidi Login
</Button>

Summary

sequenceDiagram
    actor User
    participant Website
    participant Affinidi Login
    participant Affinidi Vault
    participant Affinidi Verifier

    User->>Website: My Login
    Website->>Affinidi Login: Authenticate user
    Note over Website, Affinidi Login:  login_challenge
    Affinidi Login->>Affinidi Vault: Verify user identity
    Note over Affinidi Login, Affinidi Vault:  presentationDefinition
    Affinidi Vault->>User: Request user confirmation to share Email VC
    User->>Affinidi Vault: User confirmed consent to share Email VC
    Affinidi Vault->>Affinidi Vault: Generate VP Token from VC
    Affinidi Vault->>Affinidi Login: Send Email VP Token
    Affinidi Login->>Affinidi Verifier: Validate VP Token
    Note over Affinidi Login, Affinidi Verifier:  vp_token, presentation_submission, presentation_definition
    Affinidi Login->>Affinidi Login: Generate idToken
    Affinidi Login->>Website: Send generated idToken from VP
    Website->>User: Provide access to the user

Using the sample application, we have configured it to integrate with Affinidi Login as the OIDC provider and parse the idToken sent by the Affinidi Login to confirm the user’s successful authentication using the Affinidi Vault.