最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - Azure AD Authentication with Django on AWS ALB: Redirect URI problem - Stack Overflow

programmeradmin4浏览0评论

I am trying to integrate Microsoft authentication with my Django app using the django_auth_adfs package. However, I encountered an error regarding a mismatch in the redirect URI.

I have followed the documentation provided by django_auth_adfs for configuring Azure Active Directory integration. In my Azure portal, I registered the application and added https://myhost/oauth2/callback to the Web Redirect URLs as instructed.

When attempting to authenticate, I receive the following error message with http URI instead of https:

> AADSTS50011: The redirect URI 'http://myhost/oauth2/callback' specified in the request does not match the redirect URIs configured for the application '944fce1cxxxx-xxx-xxxx-4f2abba56fb6'.
Make sure the redirect URI sent in the request matches one added to your application in the Azure portal.
Navigate to  to learn more about how to fix this.

I have created a record for the host in route53 and configured my ALB with ACM certificate.

I am using below settings file:

from pathlib import Path
import os

BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')

DEBUG = False

SITE_ID = 1

ALLOWED_HOSTS = ['myhost']

CSRF_TRUSTED_ORIGINS = ['myhost']


# Application definition

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    'django.contrib.sites',
    'workspaces',
    'django_auth_adfs',
    'django_extensions',
]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middlewaremon.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
    "django_auth_adfs.middleware.LoginRequiredMiddleware",
]

ROOT_URLCONF = "web_workspaces.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ],
        },
    },
]

WSGI_APPLICATION = "web_workspaces.wsgi.application"

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': os.environ.get('DB_NAME', 'workspaces'),
        'USER': os.environ.get('DB_USER', 'postgres'),
        'PASSWORD': os.environ.get('DB_PASSWORD', ''),
        'HOST': os.environ.get('DB_HOST', 'localhost'),
        'PORT': os.environ.get('DB_PORT', '5432'),
    }
}


AUTH_PASSWORD_VALIDATORS = [
    {
        "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
    },
]

LANGUAGE_CODE = "en-us"

TIME_ZONE = "UTC"

USE_I18N = True

USE_TZ = True

STATIC_URL = "static/"

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

AUTHENTICATION_BACKENDS = (
    'django_auth_adfs.backend.AdfsAuthCodeBackend',
)
LOGIN_URL = "django_auth_adfs:login"
LOGIN_REDIRECT_URL = "/"
client_id = os.getenv('MICROSOFT_CLIENT_ID')
client_secret = os.getenv('MICROSOFT_CLIENT_SECRET')
tenant_id = os.getenv('MICROSOFT_TENANT_ID')
AUTH_ADFS = {
    'AUDIENCE': client_id,
    'CLIENT_ID': client_id,
    'CLIENT_SECRET': client_secret,
    'CLAIM_MAPPING': {'first_name': 'given_name',
                      'last_name': 'family_name',
                      'email': 'upn'},
    'GROUPS_CLAIM': 'roles',
    'MIRROR_GROUPS': True,
    'USERNAME_CLAIM': 'upn',
    'TENANT_ID': tenant_id,
    'RELYING_PARTY_ID': client_id,
}

# Security settings for HTTPS
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True

and below is my urls configuration:

urlpatterns = [
    path("", include("workspaces.urls")),
    path('health/', health_check, name='health_check'),
    path('oauth2/', include('django_auth_adfs.urls')),
    path('admin/', admin.site.urls)
]
urlpatterns += staticfiles_urlpatterns()

What could be causing this redirect URI mismatch error despite configuring the correct redirect URI in the Azure portal? Is there anything additional I need to configure or check within my Django or Azure settings to resolve this issue?

Any insights or guidance on resolving this issue would be greatly appreciated. Thank you!

I am trying to integrate Microsoft authentication with my Django app using the django_auth_adfs package. However, I encountered an error regarding a mismatch in the redirect URI.

I have followed the documentation provided by django_auth_adfs for configuring Azure Active Directory integration. In my Azure portal, I registered the application and added https://myhost/oauth2/callback to the Web Redirect URLs as instructed.

When attempting to authenticate, I receive the following error message with http URI instead of https:

> AADSTS50011: The redirect URI 'http://myhost/oauth2/callback' specified in the request does not match the redirect URIs configured for the application '944fce1cxxxx-xxx-xxxx-4f2abba56fb6'.
Make sure the redirect URI sent in the request matches one added to your application in the Azure portal.
Navigate to https://aka.ms/redirectUriMismatchError to learn more about how to fix this.

I have created a record for the host in route53 and configured my ALB with ACM certificate.

I am using below settings file:

from pathlib import Path
import os

BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')

DEBUG = False

SITE_ID = 1

ALLOWED_HOSTS = ['myhost']

CSRF_TRUSTED_ORIGINS = ['myhost']


# Application definition

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    'django.contrib.sites',
    'workspaces',
    'django_auth_adfs',
    'django_extensions',
]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middlewaremon.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
    "django_auth_adfs.middleware.LoginRequiredMiddleware",
]

ROOT_URLCONF = "web_workspaces.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ],
        },
    },
]

WSGI_APPLICATION = "web_workspaces.wsgi.application"

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': os.environ.get('DB_NAME', 'workspaces'),
        'USER': os.environ.get('DB_USER', 'postgres'),
        'PASSWORD': os.environ.get('DB_PASSWORD', ''),
        'HOST': os.environ.get('DB_HOST', 'localhost'),
        'PORT': os.environ.get('DB_PORT', '5432'),
    }
}


AUTH_PASSWORD_VALIDATORS = [
    {
        "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
    },
]

LANGUAGE_CODE = "en-us"

TIME_ZONE = "UTC"

USE_I18N = True

USE_TZ = True

STATIC_URL = "static/"

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

AUTHENTICATION_BACKENDS = (
    'django_auth_adfs.backend.AdfsAuthCodeBackend',
)
LOGIN_URL = "django_auth_adfs:login"
LOGIN_REDIRECT_URL = "/"
client_id = os.getenv('MICROSOFT_CLIENT_ID')
client_secret = os.getenv('MICROSOFT_CLIENT_SECRET')
tenant_id = os.getenv('MICROSOFT_TENANT_ID')
AUTH_ADFS = {
    'AUDIENCE': client_id,
    'CLIENT_ID': client_id,
    'CLIENT_SECRET': client_secret,
    'CLAIM_MAPPING': {'first_name': 'given_name',
                      'last_name': 'family_name',
                      'email': 'upn'},
    'GROUPS_CLAIM': 'roles',
    'MIRROR_GROUPS': True,
    'USERNAME_CLAIM': 'upn',
    'TENANT_ID': tenant_id,
    'RELYING_PARTY_ID': client_id,
}

# Security settings for HTTPS
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True

and below is my urls configuration:

urlpatterns = [
    path("", include("workspaces.urls")),
    path('health/', health_check, name='health_check'),
    path('oauth2/', include('django_auth_adfs.urls')),
    path('admin/', admin.site.urls)
]
urlpatterns += staticfiles_urlpatterns()

What could be causing this redirect URI mismatch error despite configuring the correct redirect URI in the Azure portal? Is there anything additional I need to configure or check within my Django or Azure settings to resolve this issue?

Any insights or guidance on resolving this issue would be greatly appreciated. Thank you!

Share Improve this question asked Mar 22 at 8:44 roshanroshan 11 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 0

You configured:

https://myhost/oauth2/callback

but the application is using:

http://myhost/oauth2/callback

发布评论

评论列表(0)

  1. 暂无评论