如何在 Django Web 应用程序中使用 Microsoft easyauth?

问题描述 投票:0回答:1

我在 Azure 上托管一个 django 项目,我需要使用 Microsoft 登录该项目。我无法安装任何第三方软件包,例如 django_microsoft_auth,因此需要从头开始编写。 我需要能够:

  1. 防止任何未登录的用户访问任何视图
  2. 有不同的“组”和不同的访问级别

我对 Django 用户系统相当熟悉,所以如果有一种方法可以利用它,那将非常方便,但任何有效的方法对我来说都可以。 如果有人有任何资源可以向我指出,或者类似的问题,这将非常有帮助。谢谢!

azure authentication django-rest-framework azure-active-directory
1个回答
0
投票

我尝试了以下 Django 代码来防止未经授权的用户访问视图。

代码:

views.py:

from django.shortcuts import render
from django.conf import settings
import requests

ms_identity_web = settings.MS_IDENTITY_WEB
def index(request):
    return render(request, "auth/status.html")

@ms_identity_web.login_required
def token_details(request):
    return render(request, 'auth/token.html')

@ms_identity_web.login_required
def call_ms_graph(request):
    ms_identity_web.acquire_token_silently()
    graph = 'https://graph.microsoft.com/v1.0/users'
    authZ = f'Bearer {ms_identity_web.id_data._access_token}'
    results = requests.get(graph, headers={'Authorization': authZ}).json()

    if 'value' in results:
        results ['num_results'] = len(results['value'])
        results['value'] = results['value'][:5]
    return render(request, 'auth/call-graph.html', context=dict(results=results))

settings.py:

from pathlib import Path
import os

BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = '=o7q14#fzv9&rfqy4ub_biym+osmoll)e2z)^*q__7ik6p&!ls'
DEBUG = True

ALLOWED_HOSTS = ['django-call-graph.azurewebsites.net', 'localhost', '<Azurewebapp_name>.azurewebsites.net']

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'Sample.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['Sample/templates'],
        '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',
                'Sample.context_processors.context',
            ],
        },
    },
]

WSGI_APPLICATION = 'Sample.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

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_L10N = True
USE_TZ = True

STATIC_ROOT = os.path.join(BASE_DIR, 'Sample/static_collected')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    BASE_DIR / "Sample/static"
]

# SECURE_SSL_REDIRECT = True
# SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

from ms_identity_web.configuration import AADConfig
from ms_identity_web import IdentityWebPython
AAD_CONFIG = AADConfig.parse_json(file_path='aad.config.json')
MS_IDENTITY_WEB = IdentityWebPython(AAD_CONFIG)
ERROR_TEMPLATE = 'auth/{}.html' 
MIDDLEWARE.append('ms_identity_web.django.middleware.MsalMiddleware')

aad.config.json:

{
    "type": {
        "client_type": "CONFIDENTIAL",
        "authority_type": "SINGLE_TENANT",
        "framework": "DJANGO"
    },
    "client": {
        "client_id": "<client_ID>",
        "client_credential": "<client_secret>",
        "authority": "https://login.microsoftonline.com/<tenant_ID>"
    },
    "auth_request": {
        "redirect_uri": null,
        "scopes": [],
        "response_type": "code"
    },
    "flask": null,
    "django": {
        "id_web_configs": "MS_ID_WEB_CONFIGS",
        "auth_endpoints": {
            "prefix": "auth",
            "sign_in": "sign_in",
            "edit_profile": "edit_profile",
            "redirect": "redirect",
            "sign_out": "sign_out",
            "post_sign_out": "post_sign_out"
        }
    }
}

要求.txt:

django
requests
git+https://github.com/azure-samples/ms-identity-python-utilities@main

我将以下 URL 添加到身份验证中的 Azure AD 应用程序,如下所示:

http://localhost:8000/auth/redirect
https://kamdjangoap.azurewebsites.net/auth/redirect

enter image description here

我执行了以下命令进行迁移并运行 Django 应用程序:

python manage.py migrate
python manage.py runserver localhost:8000

enter image description here

本地输出:

enter image description here

enter image description here

enter image description here

将项目部署到 Azure Web 应用程序之前,将以下行插入到 settings.py 文件中;否则,您可能会遇到 HTTP 重定向错误。

SECURE_SSL_REDIRECT = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

Azure Web 应用程序输出:

enter image description here

enter image description here

参考:请参阅此 GitHub 存储库以获取完整代码。

© www.soinside.com 2019 - 2024. All rights reserved.