Django REST Framework用django_auth_adfs令牌认证遇401错误求助
问题:Django REST Framework配合django_auth_adfs移除SessionAuthentication后令牌认证失败
项目环境
- Django 5.0.4
- 认证后端:django_auth_adfs(Azure Active Directory)
- API服务框架:Django REST Framework
现象对比
保留SessionAuthentication时
配置如下:
REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'django_auth_adfs.rest_framework.AdfsAccessTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), }
此时可在REST Framework可浏览视图中完成授权,且能正常发送需认证的POST请求。
仅保留AdfsAccessTokenAuthentication时
配置修改为:
REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'django_auth_adfs.rest_framework.AdfsAccessTokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), }
系统返回HTTP 401未授权错误,错误信息为"Authentication credentials were not provided.",Postman也无法正常发送请求。
完整settings.py配置
""" Django settings for core project. Generated by 'django-admin startproject' using Django 5.0.4. For more information on this file, see https://docs.djangoproject.com/en/5.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/5.0/ref/settings/ """ from pathlib import Path import os from dotenv import load_dotenv load_dotenv() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.getenv('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['my_domain'] AUTHENTICATION_BACKENDS = [ 'django_auth_adfs.backend.AdfsAuthCodeBackend', ] # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", # Installed apps 'django_auth_adfs', 'bench', 'api', 'rest_framework', ] 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", # Other Middlewares 'django_auth_adfs.middleware.LoginRequiredMiddleware', ] ROOT_URLCONF = "core.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", 'DIRS': [ BASE_DIR / 'static/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", ], }, }, ] WSGI_APPLICATION = "core.wsgi.application" # Database # https://docs.djangoproject.com/en/5.0/ref/settings/#databases DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR / "db.sqlite3", } } # Password validation # https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators 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", }, ] # Internationalization # https://docs.djangoproject.com/en/5.0/topics/i18n/ LANGUAGE_CODE = "en-us" TIME_ZONE = "GB" USE_I18N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/5.0/howto/static-files/ STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' STATIC_ROOT = '/usr/share/nginx/static/' STATICFILES_DIRS = [ BASE_DIR / 'static', ] # Default primary key field type # https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" LOGIN_URL = 'django_auth_adfs:login' LOGOUT_URL = 'django_auth_adfs:logout' LOGIN_REDIRECT_URL = 'https://my_domain/oauth2/callback' # Client secret is not public information. Should store it as an environment variable. client_id = os.getenv('client_id') client_secret = os.getenv('client_secret') tenant_id = os.getenv('tenant_id') email_host_user = os.getenv('EMAIL_HOST_USER') email_host_password = os.getenv('EMAIL_HOST_PASSWORD') 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': 'email', 'TENANT_ID': tenant_id, 'RELYING_PARTY_ID': client_id, } EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'localhost' EMAIL_PORT = 25 EMAIL_USE_TLS = False EMAIL_USE_SSL = False DEFAULT_FROM_EMAIL = email_host_user SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = True REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'django_auth_adfs.rest_framework.AdfsAccessTokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), }
疑问与需求
- 怀疑Nginx反向代理未正确传递请求头
- 需求:仅允许Azure应用内用户访问API,无需SessionAuthentication,实现纯令牌认证
排查与解决步骤
1. 修复Nginx请求头传递
如果使用Nginx反向代理,默认不会转发Authorization请求头,需在Nginx的location配置中添加:
proxy_set_header Authorization $http_authorization; proxy_pass_header Authorization;
确保Django能接收到前端传递的Bearer令牌。
2. 确认令牌传递格式
Postman或前端请求时,必须在请求头中正确设置:
Authorization: Bearer <你的Azure AD访问令牌>
注意Bearer后必须加空格,令牌字符串不能有多余空格或换行。
3. 校验django_auth_adfs配置
- 确认
AUTH_ADFS中的AUDIENCE、RELYING_PARTY_ID与Azure AD应用注册中的受众完全一致 - 检查
TENANT_ID是否正确,避免令牌验证时租户不匹配
4. 调整LoginRequiredMiddleware影响
当前启用的django_auth_adfs.middleware.LoginRequiredMiddleware会强制所有视图走会话登录,与REST Framework的令牌认证逻辑冲突。
- 临时注释该中间件测试,如果认证恢复正常,可通过配置排除API路径:
AUTH_ADFS_LOGIN_EXEMPT_URLS = [ '/api/', # 排除所有API路径 '/api/*', ]
5. 开启调试日志定位问题
在settings.py中添加日志配置,查看认证过程的详细错误:
LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { 'django_auth_adfs': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': True, }, 'django.request': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': True, }, }, }
运行项目后查看控制台输出,确认Django是否收到Authorization头,以及令牌验证的具体失败原因。
内容的提问来源于stack exchange,提问作者Arad Soutehkeshan
相关产品推荐
相关产品推荐

