A configurable Django Allauth provider for Vipps Login.
Project description
Django Allauth Vipps Provider
A complete django-allauth provider for Vipps Login, supporting both traditional web and modern API (dj-rest-auth) authentication flows.
This package provides a configurable, reusable Django app that allows users to sign in to your project using their Vipps account, making it easy to integrate Norway's most popular payment and identity solution.
Features
- Integrates seamlessly with
django-allauth's social account framework. - Supports API-first authentication flows via
dj-rest-authfor use with SPAs (React, Vue, etc.) or mobile apps. - Configurable for both Vipps Test and Production environments.
- Allows customization of requested scopes (e.g., name, email, phone number).
- Fully tested and documented.
1. Installation & Setup
Prerequisites
This package assumes you have a Django project with django-allauth already installed and configured. If not, please follow the django-allauth installation guide first.
Step 1: Install the Package
Install using pip or your project's dependency manager.
pip install django-allauth-vipps
(Or poetry add django-allauth-vipps if you use Poetry)
Step 2: Update Django Settings
Add vipps_auth to your INSTALLED_APPS in your Django settings.py. It must be placed after the standard allauth apps.
# settings.py
INSTALLED_APPS = [
# ... other apps
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites', # Required by allauth
# Allauth apps
'allauth',
'allauth.account',
'allauth.socialaccount',
# Add the Vipps provider app
'vipps_auth',
]
# Required by allauth
SITE_ID = 1
# Ensure you have authentication backends configured
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend',
]
Step 3: Run Database Migrations
Run migrations to ensure the allauth models are created in your database.
python manage.py migrate
Step 4: Configure on Vipps Developer Portal
- Log in to the Vipps MobilePay Developer Portal.
- Navigate to the "Developer" section and select your profile.
- Add a new sale unit (
salgsenhet) or use an existing one. - Under the sale unit, go to the "Logg inn med Vipps" tab and get your credentials:
- Client ID
- Client Secret
- In the "Redirect URIs" section, add the URL that Vipps will redirect users back to after they log in. This is a critical step.
- For standard web flows:
https://yourdomain.com/accounts/vipps/login/callback/ - For API/SPA flows: This should be the URL of your frontend application that handles the callback, e.g.,
https://my-react-app.com/auth/callback/vipps
- For standard web flows:
Step 5: Configure in Django Admin
- Start your Django server and log in to the admin panel.
- Go to "Social applications" and click "Add social application".
- Fill out the form:
- Provider: Choose Vipps from the dropdown.
- Name: A descriptive name (e.g., "My Website Vipps Login").
- Client id: Your Vipps
client_idfrom the portal. - Secret key: Your Vipps
client_secretfrom the portal. - Sites: Select your site and move it to the "Chosen sites" box.
- Save the application.
2. Usage
For Traditional Django Websites
If you are using server-rendered templates, you can add a Vipps login button easily with the provider_login_url template tag.
In your template (login.html):
{% load socialaccount %}
<h2>Login</h2>
<a href="{% provider_login_url 'vipps' %}">Log In with Vipps</a>
django-allauth will handle the entire redirect and callback flow automatically.
For REST APIs (with dj-rest-auth)
This is the most common use case for modern frontends (React, Vue, mobile apps). The flow involves your frontend getting an authorization code from Vipps and exchanging it for a JWT token from your backend.
Step 1: Create the API Endpoint
In your project's urls.py, create a login view that uses the VippsOAuth2Adapter.
# your_project/urls.py
from django.urls import path
from dj_rest_auth.registration.views import SocialLoginView
from allauth.socialaccount.providers.oauth2.client import OAuth2Client
from vipps_auth.views import VippsOAuth2Adapter
# This view connects dj-rest-auth to our Vipps adapter
class VippsLoginAPI(SocialLoginView):
adapter_class = VippsOAuth2Adapter
client_class = OAuth2Client
# This MUST match the redirect URI you set in the Vipps Portal for your frontend
callback_url = "YOUR_FRONTEND_CALLBACK_URL"
urlpatterns = [
# ... your other urls
path("api/v1/auth/vipps/", VippsLoginAPI.as_view(), name="vipps_login_api"),
]
Step 1.1: If step 1 fails
If for some reason step 1 fails, you can try to use basic auth.
# your_project/urls.py
from django.urls import path
from dj_rest_auth.registration.views import SocialLoginView
from allauth.socialaccount.providers.oauth2.client import OAuth2Client
from vipps_auth.views import VippsOAuth2Adapter
# 1. Create a custom client class that uses HTTP Basic auth when
# exchanging the authorization code. In production Vipps expects the
# `client_id` and `client_secret` to be provided via the
# `Authorization` header, so we enable `basic_auth`.
class VippsBasicAuthClient(OAuth2Client):
def __init__(self, *args, **kwargs):
# Use HTTP Basic auth for the token request
kwargs['basic_auth'] = True
super().__init__(*args, **kwargs)
# This view connects dj-rest-auth to our Vipps adapter
class VippsLoginAPI(SocialLoginView):
adapter_class = VippsOAuth2Adapter
client_class = VippsBasicAuthClient
# This MUST match the redirect URI you set in the Vipps Portal for your frontend
callback_url = "YOUR_FRONTEND_CALLBACK_URL"
urlpatterns = [
# ... your other urls
path("api/v1/auth/vipps/", VippsLoginAPI.as_view(), name="vipps_login_api"),
]
Step 2: The Frontend Flow
-
Redirect to Vipps: Your frontend redirects the user to the Vipps authorization URL. You can get this URL from your provider's
get_authorize_url()method or construct it manually. -
Handle the Callback: After the user logs in, Vipps redirects them to your
callback_url(e.g.,https://my-react-app.com/auth/callback/vipps) with a code in the query parameters:?code=ABC-123...&state=... -
Exchange Code for JWT: Your frontend grabs the
codefrom the URL and sends it to your Django API endpoint.Example using JavaScript
fetch:async function exchangeCodeForToken(authCode) { try { const response = await fetch('https://yourdomain.com/api/v1/auth/vipps/', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ code: authCode }), }); if (!response.ok) { throw new Error('Failed to log in with Vipps'); } const data = await response.json(); // The data object now contains your JWTs // { "access": "...", "refresh": "..." } console.log(data); // Save tokens to local storage and set user as logged in } catch (error) { console.error('Vipps login error:', error); } }
3. Advanced Configuration
You can customize the provider's behavior by adding a VIPPS_AUTH_SETTINGS dictionary to your project's settings.py.
Example settings.py:
# settings.py
VIPPS_AUTH_SETTINGS = {
# The base URL for the Vipps API.
# Default: "https://apitest.vipps.no" (for testing)
# For production, use: "https://api.vipps.no"
"BASE_URL": "https://api.vipps.no",
# The scopes (permissions) you request from the user.
# Default: ["openid", "name", "email", "phoneNumber"]
"SCOPES": [
"openid",
"name",
"email",
],
# If True, login will fail if Vipps reports the user's email is not verified.
# Recommended to keep this as True for security.
# Default: True
"EMAIL_VERIFIED_REQUIRED": True,
}
4. Development & Testing
To work on this package locally:
- Clone the repository:
git clone https://github.com/danpejobo/django-allauth-vipps.git - Navigate to the directory:
cd django-allauth-vipps - Install all dependencies:
poetry install - Activate the virtual environment:
poetry shell - Run the test suite:
poetry run pytest
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file django_allauth_vipps-0.1.1.tar.gz.
File metadata
- Download URL: django_allauth_vipps-0.1.1.tar.gz
- Upload date:
- Size: 8.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.6.1 CPython/3.11.6 Linux/5.4.0-204-generic
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
9aeb5b7f5b78aa74da96dcf4c8971f4b86120296a65250caefffa349f97e054e
|
|
| MD5 |
bedf34d1d707a34464dee4b95786c160
|
|
| BLAKE2b-256 |
bda8f3afaa956cf5f0182f0536d0ec52cf363b3d7d63921923753b38a4dd5dfa
|
File details
Details for the file django_allauth_vipps-0.1.1-py3-none-any.whl.
File metadata
- Download URL: django_allauth_vipps-0.1.1-py3-none-any.whl
- Upload date:
- Size: 9.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.6.1 CPython/3.11.6 Linux/5.4.0-204-generic
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
8bbb33aa578f4bdea5114a297bc1d8e14b9225135078512091ae5a98dab59173
|
|
| MD5 |
826c6fd7b34f5ee41f41b7edab472ade
|
|
| BLAKE2b-256 |
3864b8441500f7030ab92cb94bffaeb6d2bd3ca103b03fba7ba00c70a8ab0539
|