Return Login and Redirect Views by Hardcoding Social Account Provider in django-allauth (When Using AWS Cognito, etc.)

Django
2024-12-14 04:46 (15 months ago)
Authcraft
Play a song themed on this article

How to Create a Login View in Django Allauth Without Specifying the Social Account Backend in the URL

This can be useful if you're using only one backend like AWS Cognito.

Login View

To display a login button:

from allauth.socialaccount.providers.amazon_cognito.views import oauth2_login

async def login_view(request):
    return oauth2_login(request)

View to Redirect to the Login URL

To redirect to the managed login URL of Cognito:

Settings

SOCIALACCOUNT_LOGIN_ON_GET = True
from allauth.socialaccount.providers.amazon_cognito.views import oauth2_login

async def login_view(request):
    return oauth2_login(request)

Alternatively:

from allauth.socialaccount.providers.amazon_cognito.views import oauth2_login, AmazonCognitoOAuth2Adapter

def login_redirect_view(request):
    adapter = AmazonCognitoOAuth2Adapter(request)
    provider = adapter.get_provider()
    return provider.redirect_from_request(request)

Other Recommended Settings for Allauth

Settings

LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = 'https://<your-cognito-managed-url>/logout?client_id=<cognito-client-id>>&logout_uri=https%3A%2F%2F<your-webapp>'  # NOQA
ACCOUNT_EMAIL_VERIFICATION = 'none'
SOCIALACCOUNT_ONLY = True

Categories

Archive