# Affinidi Login Integration using Flask, Authlib and Auth0

> Use this guide to learn how to integrate Affinidi Login on your projects.

[ Auth0](https://auth0.com/)
                [ Python](https://www.python.org/)
                [ Flask]()
                [ authlib](https://authlib.org/)

A code sample using Flask framework and uses AuthLib library to enable passwordless login using Auth0 IDP.

## 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 the Affinidi CLI. Follow the guide below if it hasn’t been installed.

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

- 
Make sure you have Git installed on your machine. Follow [this guide](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) on how to install Git.

- 
Create an [Auth0 tenant](https://auth0.com/docs/get-started/auth0-overview/create-tenants) or sign-in to your existing tenant account where you want to integrate Affinidi Login

- 
Create a [Regular Web Application](https://auth0.com/docs/get-started/auth0-overview/create-applications/regular-web-apps) in Auth0 and set up the necessary fields based on your application’s structure.

In this guide, set the following fields in the Auth0 Regular Web Application:

- Allowed Callback URLs: http://localhost:8101/auth

- Allowed Logout URLs: http://localhost:8101

- Allowed Web Origins: http://localhost:8101

## Download the Application

You can download as ZIP file the code sample from the [GitHub Repo](https://github.com/affinidi/reference-app-affinidi-vault/tree/main/samples/auth0-flask-authlib) or generate it using Affinidi CLI with the following command:

```Bash
affinidi generate app --provider=auth0 --framework=flask --library=authlib --path=affinidi-login-refcodes
```

Select n when prompted to Automatically configure sample app environment, we will configure it later.

The above command will generate the code sample in the affinidi-login-refcodes directory.

    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.

## Install Dependencies

After successfully generating the code sample, go to the affinidi-login-refcodes directory and install the required dependencies using the following commands:

```Bash
pip install -r requirements.txt
```

## Create Login Configuration

Name: Affinidi Login Sample

Redirect URIs: https://<Auth0_App.Domain>/login/callback

Get the Auth0 Domain from the Regular Web Application created previously.

        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='Affinidi Login Sample' --redirect-uris='https://.us.auth0.com/login/callback'
```

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

Learn more on how to manage your Login Configurations using [Affinidi CLI](/dev-tools/affinidi-cli/manage-login.md).

        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.

Learn more about customising the Presentation Definition and ID Token using [this guide](/products/affinidi-elements/affinidi-login/presentation-definition-id-token-mapping.md).

    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.

## Set up the Auth0 Social Connection

We create a Social Connection in Auth0, integrating Affinidi Login as the identity provider for authenticating users. Additionally, we configure Auth0 to parse the idToken provided by Affinidi Login once users verify their identity through Affinidi Vault.

In Auth0 Dashboard, go to Authentication > Social and click on Create Connection

Select Create Custom and set the following fields in the Auth0 with the values below:

- Authorization URL: <LoginConfig.auth.Issuer>/oauth2/auth

- Token URL: <LoginConfig.auth.Issuer>/oauth2/token

- Scope: openid offline_access

- Client ID: <LoginConfig.auth.ClientID>

- Client Secret: <LoginConfig.auth.ClientSecret>

The <LoginConfig.auth.*> are values from Login Configuration.

Copy the code below and paste it in the Fetch User Profile Script of the Social Connection

This script is called after the user consented to share their email address from their Affinidi Vault account. Auth0 executes this script and extracts the user_id, email, and the custom fields where additional data are populated like user address from the idToken provided by Affinidi Login after successful login:

```Javascript
function fetchUserProfile(accessToken, context, callback) {
  const idToken = JSON.parse(
    Buffer.from(context.id_token.split(".")[1], "base64").toString()
  );

  const profile = {
    user_id: idToken.sub,
    email: idToken.custom.find((c) => c.email).email,
    profile: idToken.custom,
  };

  callback(null, profile, context);
}
```

Update the fetch profile script based on the structure of the ID Token mapped in the Login Configuration.

Once you are done setting up, enable the application to use the custom Social Connection in the Applications view. This will enhance the Auth0 to use the Affinidi Vault as the identity provider to enable a decentralised identity.

## Set up the Application

Once the Web Application and Social Connection configuration is completed, set up the Auth0 client credentials provided to enable Auth0 login enhanced by Affinidi Login.

Copy and set up the environment variables:

```Bash
cp .env.example .env
```

Set the following variables with the values provided in the Auth0 Regular Web Application created previously:

```Bash
PROVIDER_CLIENT_ID=""
PROVIDER_CLIENT_SECRET=""
PROVIDER_ISSUER=""
```

The <Auth0_App.*> are values from Auth0 Application.

## Run the Application

After installing the dependencies and setting up the required details in the application, run the following command to start the app locally:

```Bash
python -m flask run -p 8101
```

Once it is successfully started, visit the app using the link [http://localhost:8101](http://localhost:8101).

## Integration-related Changes

To enable a seamless passwordless login experience with Affinidi Login, refer to the following key changes were implemented:

- Imported Authlib to enable OAuth flow.

- Implemented the following function in the ./app.py:

- Registered affinidi as OAuth provider with the client credentials.

- login endpoint to initiate the Affinidi Login flow using Authlib.

- auth endpoint to receive the response from Affinidi Login (e.g. idToken, accessToken).

Explore the sample implementation to learn more about how the integration works.
