# Affinidi Login with Python

> In this guide, learn how to enable passwordless login in your application using Django Framework and Authlib.

The Affinidi Login is a passwordless authentication solution that verifies user identity using [Affinidi Vault](/products/affinidi-elements/affinidi-vault/how-affinidi-vault-works.md) as the identity provider managed by the end-user.

In this lab, we will use the [Django](https://www.djangoproject.com/) framework with [Authlib](https://docs.authlib.org/en/latest/) from the available sample applications to take you through the step-by-step guide for creating a Login Configuration and setting up the application to implement passwordless authentication for end-users.

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

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

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

- Install Python on your machine if you haven’t installed yet using [this guide](https://www.python.org/downloads/).

## Download Application

You can [clone](https://github.com/affinidi/reference-app-affinidi-vault/tree/main/samples/affinidi-django-authlib) this sample application from our Github and start exploring how to integrate Affinidi Login to provide a passwordless login experience for your end-users.

    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.

## Create Login Configuration

To create a [Login Configuration](/products/affinidi-elements/affinidi-login/login-configuration.md), 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:

Django Sample App Settings:

Name: Django App

Redirect URIs: http://localhost:8000/callback

        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='Django App' --redirect-uris='http://localhost:8000/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.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.

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 Sample Application

After creating the Login Configuration required to set up the sample application. Let’s start setting up the Django application by configuring the following settings:

#### Configure Env Variables

Create the .env file using the following command:

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

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

```JSON
{
  "auth": {
    "clientId": "",
    "clientSecret": "",
    "issuer": "https://

.apse1.login.affinidi.io"
  }
}
```

Set the following fields in the .env file

```yaml
PROVIDER_CLIENT_ID=""
PROVIDER_CLIENT_SECRET=""
PROVIDER_ISSUER=""
```

#### Install Dependencies

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

It will install all the required libraries for the sample application.

#### Apply Settings

Run the migration script to propagate changes to the model:

```Bash
python manage.py migrate
```

#### Run Sample Application

Run the application using the runserver command:

```Bash
python manage.py runserver
```

After successfully running the command, go to [http://localhost:8000](http://localhost:8000) to access the page with the Affinidi Login button.

## Key Changes to Sample Application

#### AuthLib for OIDC

In this sample app, we have defined the requirements.txt file to import the AuthLib library, enabling OAuth and OpenID Connect to integrate Affinidi Login to authenticate users.

```env
Django==4.2.6
Authlib==1.2.1
requests==2.31.0
python-dotenv==1.0.0
```

#### Enabling Affinidi Login

In views.py, we have imported AuthLib and registered affinidi as the Auth provider for our sample application. In the oauth.register call, we have provided the client credentials and issuer URL generated after creating Login Configuration.

```Python
import json
from authlib.integrations.django_client import OAuth
from django.conf import settings
from django.shortcuts import redirect, render, redirect
from django.urls import reverse

oauth = OAuth()

oauth.register(
    "affinidi",
    client_id=settings.PROVIDER_CLIENT_ID,
    client_secret=settings.PROVIDER_CLIENT_SECRET,
    client_kwargs={
        'scope': 'openid offline_access',
        'token_endpoint_auth_method': 'client_secret_post',
    },
    server_metadata_url=f"{settings.PROVIDER_ISSUER}/.well-known/openid-configuration",
)

def login(request):
    redirect_uri = request.build_absolute_uri(reverse('callback'))
    return oauth.affinidi.authorize_redirect(request, redirect_uri)

def callback(request):
    token = oauth.affinidi.authorize_access_token(request)
    request.session["user"] = token['userinfo']
    return redirect(request.build_absolute_uri(reverse("index")))

def logout(request):
    request.session.pop('user', None)
    return redirect('/')

def index(request):
    user = request.session.get("user")
    if user:
        if user["custom"] and len(user["custom"][1])>0:
            email = user["custom"][1]
        else:
            email = None
    else:
        email = None

    if email is None:
        return render(
            request,
            "index.html",
            context={
            "session": email,
            "pretty": json.dumps(request.session.get("user"), indent=4),
            },
        )
    else:
        return render(
            request,
            "loggedin.html",
            context={
                "session": email,
                "pretty": json.dumps(request.session.get("user"), indent=4),
            },
        )
```

After enabling OAuth and registering affinidi as the provider, we have defined 2 key routes to enable Affinidi Login in the sample application.

- 
login that OAuth library and triggers a redirect to Affinidi Login flow using the credentials provided in the OAuth library.

- 
callback that parses the ID Token using OAuth library sent by Affinidi Login after successful authentication of the user. At the same time, we started the user session with the uder info extracted from the ID Token.

## Summary

```mermaid
sequenceDiagram
    actor User
    participant Django
    participant Affinidi Login
    participant Affinidi Vault
    participant Affinidi Verifier

    User->>Django: My Login
    Django->>Affinidi Login: Authenticate user
    Note over Django, 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->>Django: Send generated idToken from VP
    Django->>User: Provide access to the user
```

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