You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助Django+Auth0+Graphene集成配置指南及相关参考链接

Django + Auth0 + Graphene 集成配置指南

前置依赖安装

  • 安装所需的第三方包:
    pip install django graphene-django django-cors-headers python-jose[cryptography]

Auth0 控制台配置

  1. 登录Auth0控制台创建API,设置唯一API标识符,签名算法选择RS256
  2. 进入对应应用的设置页面,记录Domain、Client ID、Client Secret三个参数备用
  3. 配置允许的回调地址、注销地址、跨域源为你的Django服务访问地址

Django 服务配置

配置settings.py

  • 新增应用到INSTALLED_APPS:
INSTALLED_APPS = [
    # Django 原生应用
    'corsheaders',
    'graphene_django',
    # 你的自定义应用
]
  • 配置中间件:
MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware', # 放置在中间件列表最顶部
    # Django 原生中间件
]
  • 新增跨域配置,生产环境建议替换为指定域名列表:
    CORS_ALLOW_ALL_ORIGINS = True
  • 新增Graphene配置:
GRAPHENE = {
    'SCHEMA': '你的项目名.schema.schema',
}
  • 新增Auth0参数配置:
AUTH0_DOMAIN = '你记录的Auth0 Domain'
AUTH0_AUDIENCE = '你创建的Auth0 API标识符'
AUTH0_ALGORITHMS = ['RS256']

自定义Auth0认证后端

新建auth0_backend.py文件,编写Token验证逻辑:

import jwt
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import BaseBackend

User = get_user_model()

class Auth0Backend(BaseBackend):
    def authenticate(self, request, **kwargs):
        auth_header = request.META.get('HTTP_AUTHORIZATION', None)
        if not auth_header:
            return None
        try:
            token = auth_header.split(' ')[1]
            jsonurl = f'https://{settings.AUTH0_DOMAIN}/.well-known/jwks.json'
            jwks_client = jwt.PyJWKClient(jsonurl)
            signing_key = jwks_client.get_signing_key_from_jwt(token)
            payload = jwt.decode(
                token,
                signing_key.key,
                algorithms=settings.AUTH0_ALGORITHMS,
                audience=settings.AUTH0_AUDIENCE,
                issuer=f'https://{settings.AUTH0_DOMAIN}/'
            )
        except Exception:
            return None
        user, created = User.objects.get_or_create(
            username=payload['sub'],
            defaults={'email': payload.get('email', '')}
        )
        return user

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None
  • 将自定义认证后端加入配置:
AUTHENTICATION_BACKENDS = [
    '你的项目名.auth0_backend.Auth0Backend',
    'django.contrib.auth.backends.ModelBackend',
]

Graphene 接口权限控制

  • 公开接口无需额外配置,受保护的接口使用Django原生@login_required装饰器即可:
import graphene
from django.contrib.auth.decorators import login_required

class Query(graphene.ObjectType):
    protected_info = graphene.String()

    @login_required
    def resolve_protected_info(self, info, **kwargs):
        return f"认证成功,当前用户ID:{info.context.user.id}"

调用验证

发起GraphQL请求时,在请求头添加Authorization: Bearer <从Auth0获取的Access Token>即可正常访问受保护接口。

内容的提问来源于stack exchange,提问作者Matias

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 12:24:03