# Affinidi Login with KeyCloak

> This guide explains how to enable passwordless login in your application with KeyCloak.

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

This lab uses [NextJS](https://nextjs.org/) and [NextAuth.js](https://next-auth.js.org/) as the framework to implement Affinidi Login.

## Before you begin

- Set up Affinidi Vault account. Follow the guide below if you haven’t set it up yet.

        Set up Affinidi Vault

Set up an Affinidi Vault account using the [Web Vault](https://vault.affinidi.com) or install the Mobile Vault (for [Android](https://play.google.com/store/apps/details?id=com.affinidi.vault&pcampaignid=web_share)).

The same setup steps for Mobile Vault.

- 
Click on Get started if you are creating a new account, or click on Restore from Backup if you have an existing backup of your Affinidi Vault. Provide the passphrase to secure your Affinidi Vault.

You have the option to enable Biometrics to unlock your Affinidi Vault easily instead of using passphrase.

GIF 

- Enter your email address to register with the Affinidi Vault. An OTP will be sent to this email for verification.

GIF 

- Enter the OTP sent to the email you have provided for verification to complete the setup.

GIF 

After successfully providing the OTP, you are redirected to the Affinidi Vault dashboard.
Important Note

Remember to keep your passphrase in a secure location. Use the Passphrase Reset feature in Affinidi Vault settings to generate the PDF files and keep them safe, which you can use to recover access to your Affinidi Vault if you forget your passphrase.

- 
Install [Docker](https://www.docker.com/products/docker-desktop/) and [Docker Compose](https://docs.docker.com/compose/install/) software into your machine.

- 
Optionally, install the Affinidi CLI. Follow the guide below if you haven’t installed yet.

        Set up Affinidi CLI

- Download and install [NodeJS](https://nodejs.org/en/download) on your machine if you haven’t set it up yet.

Node Version

Affinidi CLI requires Node version 18 and above.

- Install Affinidi CLI using Node Package Manager (npm).

```bash
npm install -g @affinidi/cli
```

- Verify that the installation is successful.

```bash
affinidi --version
```

## Download Application

You can [download](/files/affinidi-login-sample-keycloak.zip) this sample application using Next.js framework and start exploring how to integrate Affinidi Login with KeyCloak as the authorisation server and Affinidi Vault as the Identity Provider to provide a passwordless login experience.

    Important Note
    The downloadable sample application is provided only as a guide to quickly explore and learn how to integrate the components of Affinidi Trust Network into your application. This is NOT a Production-ready implementation. Do not deploy this to a production environment.

## Running the Application

- Suppose this is your first time downloading the sample application. Run the following command to install the dependencies.

```bash
npm install
```

- Create the .env file in the sample application by running the following command.

```bash
cp .env.example .env
```

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

- After installing the dependencies, run the application by running the command.

```bash
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.

## Initiate KeyCloak App via Docker

In this lab, we use KeyCloak docker image to kick-start the application locally.

- 
Open your command line and go to the sample application directory.

- 
Run the following command to initiate the KeyCloak app through Docker.

```Bash
docker compose up -d
```

- Verify that the container was successfully created by running:

```Bash
docker ps
```

workshop-reference-app-keycloak-1 should be in a running status and accessible in the browser through [http://localhost:8080](http://localhost:8080).

- Login to the Administration Console using the following credentials:

Username / Password: admin / admin

## Configure KeyCloak Client

Create an OpenID Connect client to integrate with the sample application. Use the generated credentials to enable KeyCloak authentication flow.

- Go to Client and create a new client.

- In the General Settings, configure the following details and then click on Next:

- Client type: OpenID Connect

- Client ID: affinidi-keycloak

- Name: affinidi-keycloak

- 
In the Capability Config, enable both Client authentication and Authorization. Keep the default Authentication flow.

- 
In the login settings, configure the following URLs:

- Root URL: http://localhost:3000

- Home URL: http://localhost:3000

- Valid redirect URIs: http://localhost:3000/api/auth/callback/keycloak

- Web origins: http://localhost:3000

- Once you have successfully created a KeyCloak client, a Client secret is generated under the Credentials tab. We’ll use this on the later steps.

## Create Login Configuration

Having set up KeyCloak, started the KeyCloak client, and created a new client, you need to create the Affinidi Login Configuration. The authentication credentials produced by the Login Configuration serve to integrate Affinidi Login into the KeyCloak OpenID provider.

To create a Login Configuration, you can either use Affinidi CLI or [Affinidi Portal ](/dev-tools/affinidi-portal.md#create-a-login-configuration).

Expand the section below for your preferred method:

Name: My KeyCloak config

Redirect URIs: http://localhost:8080/realms/master/broker/affinidi/endpoint

        Using Affinidi CLI

- Log in to Affinidi CLI by running:

```Bash
affinidi start
```

- Once you have successfully logged in, create the Login Configuration by running:

```Bash
affinidi login create-config \
--name='My KeyCloak config' \
--redirect-uris='http://localhost:8080/realms/master/broker/affinidi/endpoint'
```

- --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:

```JSON
{
  "ari": "ari:identity:ap-southeast-1:687b8872-a618-dt63-8978-e72ac32daeb1:login_configuration/c4f74d936cd31bde1c1fd3c1050bb76s",
  "projectId": "687b8872-a618-4e52-8978-e72ac32daec2",
  "configurationId": "c4f74d936cd31bde1c1fd3c1050bb62d",
  "name": "...",
  "auth": {
    "clientId": "",
    "clientSecret": "",
    "issuer": "https://

.apse1.login.affinidi.io"
  },
  "redirectUris": [
    "..."
  ],
  "clientMetadata": {
    "name": "Login Config Name",
    "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](/dev-tools/affinidi-cli.md#affinidi-vpa-configs).

        Using Affinidi Portal

- 
Go to [Affinidi Login ](https://portal.affinidi.com/affinidiLogin) under the Services section.

- 
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.

- 
Click on create and confirm if all the details are correct.

- 
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.

- 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.

    Important

Safeguard the Client ID and Client Secret diligently; you'll need them for setting up your IdP or OIDC-compliant applications. Remember, the Client Secret will be provided only once.

## Configure KeyCloak with Affinidi Login

In these steps, you configure KeyCloak to integrate with Affinidi Login as the identity provider when authenticating users during the login flow. Use the auth credentials that Login Configuration generated.

- 
Go back to the KeyCloak Admin Console and go to Identity providers.

- 
Click on KeyCloak OpenID Connect and configure the following details:

- Alias: affinidi

- Display name: affinidi

- In the OpenID Connect settings, configure credentials that the Login Configuration generated from the previous step:

- Discovery endpoint: auth.issuer/.well-known/openid-configuration

- Client ID: set the value from the auth.clientId of the Login Configuration

- Client Secret: set the value from the auth.clientId of the Login Configuration

auth.issuer is the value from Login Configuration.

- Once you add the OpenID Connect provider details. Scroll down to Advanced section and set the following details:

- Scopes: openid offline_access

- Prompt: Login

- Enable both Store tokens and Trust email option in the Advanced settings section.

## Configure KeyCloak idToken Mapping

In these steps, add the field mappings that allow KeyCloak to map user claims from the idToken provided by Affinidi Login into KeyCloak’s own idToken, which is subsequently sent to the application integrated with KeyCloak.
 In the mapping below, we are mapping the `custom[1].email` field from the custom claim of the Affinidi Login's idToken into the `username` field of the idToken of KeyCloak. -->

In the mapping example provided, the custom[1].email field from Affinidi Login’s idToken custom claim is mapped to the username field of KeyCloak’s idToken.

- To add this, navigate to the ‘Mappers’ tab and select the ‘Add Mapper’ button.

Proceed with the following field mappings:

| Name | Mapper Type | Claims | User Attribute Name |
| username mapper | Attribute Importer | custom[1].email | username |
| email mapper | Attribute Importer | custom[1].email | email |
| firstname mapper | Attribute Importer | sub | firstName |
| lastname mapper | Attribute Importer | sub | lastName |

## Set up the Sample Application

In these steps, setup parts of the sample application to integrate KeyCloak into the sample application. The KeyCloak you integrated is configured to connect to the Affinidi Login as the identity provider.

In this guide, learn how to integrate Affinidi Login using [NextJS](https://nextjs.org/) and [NextAuth.js](https://next-auth.js.org/) with KeyCloak as authorisation server into your application.

KeyCloak is configured to connect to Affinidi Login as the Identity provider to authenticate user.

#### Configure .env file

Set the environment variables based on the credentials generated from KeyCloak client called affinidi-keycloak you have created earlier:

```yaml
PROVIDER_CLIENT_ID="affinidi-keycloak"
PROVIDER_CLIENT_SECRET=""
PROVIDER_ISSUER="http://localhost:8080/realms/master"
```

#### Configure NextAuth for Affinidi Login

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

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 KeyCloak Login as a Login Provider

In the code below, we are adding KeycloakProvider as one of the Login Provider for NextAuth.js.

Import the KeyCloak from the NextAuth.js library

```Javascript
import KeycloakProvider from "next-auth/providers/keycloak"
```

Add KeyCloak as a Login Provider

```Javascript
KeycloakProvider({
    clientId: providerClientId,
    clientSecret: providerClientSecret,
    issuer: providerIssuer,
}),
```

##### Generate JWT and Session from the idToken

In the code below, you generate a JWT and a session from the idToken that we have received from KeyCloak after successful user authentication.

```Javascript
async jwt({ token, account, profile }) {
    const email = (profile as any)?.email;
    const did = (profile as any)?.given_name;

    return {
    ...token,
    ...(email && { email }),
    ...(did && { did }),
    ...(account?.access_token && { accessToken: account?.access_token }),
    ...(account?.id_token && { idToken: account?.id_token }),
    ...(profile?.sub && { userId: profile?.sub }),
    };
},

async session({ session, token }) {
    return {
    ...session,
    ...session.user,
    ...(token.did && { did: token.did }),
    ...(token.email && { email: token.email }),
    ...(token.userId && { userId: token.userId }),
    ...(token.accessToken && { accessToken: token.accessToken }),
    ...(token.idToken && { idToken: token.idToken }),
    };
},
```

#### Enable Affinidi Login

File path: pages/sign-in/index.tsx

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

```Javascript
async function logIn() {
  // enable Affinidi Login button
  await signIn('keycloak', { callbackUrl: hostUrl })
}
```

## Summary

```mermaid
sequenceDiagram
    actor User
    participant Website
    participant KeyCloak
    participant Affinidi Login
    participant Affinidi Vault
    participant Affinidi Verifier

    User->>Website: My Login
    Website->>KeyCloak: trigger OIDC flow
    Note over Website, KeyCloak: KeyCloak OIDC credentials
    KeyCloak->>Affinidi Login: Authenticate user
    Note over KeyCloak, 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->>KeyCloak: Send generated idToken from VP
    KeyCloak->>Website: Send Mapped idToken
    Website->>User: Provide access to the user
```

In the sample application, we integrated KeyCloak as the OIDC provider and set it up to work with Affinidi Login as the identity provider. Affinidi Login interacts with the Affinidi Vault to verify the user’s identity and then supplies the VP Token, which KeyCloak uses as part of the idToken.
