Skip to main content

Custom Django authentication backend using Sign-In with Ethereum (EIP-4361) with a custom wallet user model. Available to use in django rest api or django app.

Project description

Siwe Authentication - Django

GitHub Stars GitHub Forks GitHub Issues PyPI Version GitHub Release Date

Siwe Authentication is a Django app designed for Ethereum-based authentication using the Sign-In with Ethereum (EIP-4361) standard. It allows users to sign in using their Ethereum wallets, and provides flexible settings for customization.

Table Of Contents

  1. Get Started
    1. Installation
    2. Configuration
    3. Run migrations
  2. Usage
  3. Custom Groups
  4. Django User Model
  5. Contrubuting
  6. License

Get Started

Installation

Install the package using pip with the following command:

pip install siwe-auth-django

Configuration

Add 'siwe_auth' to INSTALLED_APPS in your settings.py file:

# settings.py

INSTALLED_APPS = [
    # ...
    'siwe_auth',
    # ...
]

Add authentication configurations in your settings.py file:

# settings.py

AUTH_USER_MODEL = "siwe_auth.Wallet"
AUTHENTICATION_BACKENDS = [
    "siwe_auth.backends.SiweBackend", 
    "django.contrib.auth.backends.ModelBackend" # this is necessary if you want to use superusers in django admin authentication
    ]
SESSION_COOKIE_AGE = 3 * 60 * 60 

If you need to create a customized auth user model refer to Django User Model section (Recommended).

Add the SIWE_AUTH configuration in your settings.py file:

Available settings:

"CSRF_EXEMPT": Flag indicating whether CSRF protection is exempted for Siwe Authentication views (if you are creating an REST API must be True).
"PROVIDER": Ethereum provider URL (it is required).
"CREATE_GROUPS_ON_AUTH": Flag indicating whether to create groups on user authentication.
"CREATE_ENS_PROFILE_ON_AUTH": Flag indicating whether to create ENS profiles on user authentication.
"CUSTOM_GROUPS": List of custom groups to be created on user authentication. If you need to create more group manager refer to Custom Groups section.

# settings.py

from siwe_auth import group # needed if you want to set custom groups

# ...

SIWE_AUTH = {
    "CSRF_EXEMPT": True, # default False
    "PROVIDER": "https://mainnet.infura.io/v3/...", # required
    "CREATE_GROUPS_ON_AUTH": True, # default False
    "CREATE_ENS_PROFILE_ON_AUTH": True, # default True
    "CUSTOM_GROUPS": [
        ("usdt_owners", groups.ERC20OwnerManager(config={'contract': '0x82E...550'})),
        ("nft_owners", groups.ERC721OwnerManager(config={'contract': '0x785...3A5'})),
        # ...
    ], # default []
}

Include the Siwe Authentication URLs in your project's urls.py:

# urls.py

from django.urls import include, path

urlpatterns = [
    # ...
    path('api/auth', include('siwe_auth.urls', namespace='siwe_auth')),
    # ...
]

Run migrations:

python manage.py migrate

Usage

You need to follow this steps to successful authentication using SIWE protocol (EIP-4361):

  1. Get nonce: GET Method /api/auth/nonce.
  2. Use that nonce to create a SIWE message in frontend and sign the message with your metamask or another wallet.
  3. Login: POST Method /api/auth/login, using the message and signature. Example request body:
{
    "message": {
        "domain": "your_domain.com",
        "address": "0xA8f1...61905",
        "statement": "This is a test statement.",
        "uri": "https://your_domain.com",
        "version": "1",
        "chainId": 1,
        "nonce": "2483e73dedffbd2616773506",
        "issuedAt": "2024-01-27T18:43:48.011Z"
    },
    "signature": "0xf5b4ea...7bda4e177276dd1c"
}
  1. Now you have the sessionid in cookies so you can use it for authenticated required views.
  2. Refresh the sessionid: POST Method api/auth/refresh.
  3. Verify if you are authenticated: GET Method api/auth/verify.
  4. Logout: POST Method api/auth/logout.

Custom Groups

Three custom group managers are provided by default:
ERC20OwnerManager
ERC721OwnerManager
ERC1155OwnerManager

You can create more group managers by extending the GroupManager class:

from web3 import HTTPProvider
from siwe_auth.groups import GroupManager

class MyCustomGroup(GroupManager):
    def __init__(self, config: dict):
        # Your custom logic
        pass

    def is_member(self, wallet: object, provider: HTTPProvider) -> bool:
        # Your custom logic to determine membership
        pass

You can create custom groups in your settings.py:

# settings.py

from siwe_auth import group # needed if you want to set custom groups

# ...

SIWE_AUTH = {
    # ...
    "CUSTOM_GROUPS": [
        ("usdt_owners", groups.ERC20OwnerManager(config={'contract': '0x82E...550'})),
        ("nft_owners", groups.ERC721OwnerManager(config={'contract': '0x785...3A5'})),
        ("token_owners", groups.ERC1154OwnerManager(config={'contract': '0x872...5F5'})),
        # ...
    ], # default []
}

Then you can manage these groups with the django GroupManager, example:

from django.contrib.auth.models import Group
# ...

usdt_owners_group = Group.objects.get(name='usdt_owners')
all_usdt_owners = usdt_owners_group.user_set.all()
# ...

Django User Model

By default, Siwe Authentication uses the Wallet model as the user model. If you prefer to use a specific user model, you can either use the provided AbstractWallet model or create your own user model. For more details, refer to the Configuration section.

# Django project your_app/models.py

from siwe_auth.models import AbstractWallet

class MyUserModel(AbstractWallet):
    # Add your custom fields here

If you use a customized user model you need to register a customized admin site.

# Django project your_app/admin.py

from django.contrib import admin

from django.contrib.auth import get_user_model
from siwe_auth.admin import WalletBaseAdmin

WalletModel = get_user_model()


# You can inherit from siwe_auth.admin.WalletBaseAdmin or from django.contrib.auth.admin.BaseUserAdmin if you preffer.
class WalletAdmin(WalletBaseAdmin): 
    # Add your custom configuration here
    
admin.site.register(WalletModel, WalletAdmin)

Contributing

Contributions are welcome! Please create issues for bugs or feature requests. Pull requests are encouraged.

License

This project is licensed under the MIT License - see the LICENSE file for details.

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

siwe_auth_django-3.0.3.tar.gz (16.9 kB view details)

Uploaded Source

Built Distribution

siwe_auth_django-3.0.3-py3-none-any.whl (18.5 kB view details)

Uploaded Python 3

File details

Details for the file siwe_auth_django-3.0.3.tar.gz.

File metadata

  • Download URL: siwe_auth_django-3.0.3.tar.gz
  • Upload date:
  • Size: 16.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/4.0.2 CPython/3.11.8

File hashes

Hashes for siwe_auth_django-3.0.3.tar.gz
Algorithm Hash digest
SHA256 deab8cebd53800a4fc27ea92a56e0a2feb3238f2c85f0eb158a1817f761dde1f
MD5 860ef6ea03cdf5c232bd283dbe8128e9
BLAKE2b-256 c0fbc16939eef963837b6145ff491536cd702f33c689b21b00088265917cd4ac

See more details on using hashes here.

File details

Details for the file siwe_auth_django-3.0.3-py3-none-any.whl.

File metadata

File hashes

Hashes for siwe_auth_django-3.0.3-py3-none-any.whl
Algorithm Hash digest
SHA256 11ef039d19542af0a3a90e680a56b9a969992c79939a086a0b96e057a29d270b
MD5 7a46899455bfaf89be9f4b4f31300a58
BLAKE2b-256 1e97d4ca5e41017adc7a373f4031d15f04dec7133ebf25c7cc84a31a65e7a398

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page