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

如何在Django REST Framework中结合OIDC登录进行测试?

解决Django REST Framework API结合mozilla-django-oidc的认证测试问题

针对你在测试带IsAuthenticated权限的DRF API时遇到的问题,提供两种实用方案:

方案1:单元测试用force_authenticate直接模拟认证

这种方式无需生成真实令牌,直接强制请求处于认证状态,适合快速验证API逻辑:

from django.contrib.auth import get_user_model
from django.urls import reverse
from rest_framework.test import APITestCase

User = get_user_model()

class YourAPITestCase(APITestCase):
    def test_authenticated_api_access(self):
        # 创建测试用户(模拟Keycloak同步到Django的用户)
        user = User.objects.create_user(username="test_user", email="test@example.com")
        
        # 强制将当前请求关联到该用户
        self.client.force_authenticate(user=user)
        
        # 发送认证后的请求
        response = self.client.get(reverse("foo:bar"))
        
        # 验证请求成功
        self.assertEqual(response.status_code, 200)

方案2:集成测试模拟Keycloak获取真实JWT令牌

如果需要贴近生产环境的认证流程测试,可直接调用Keycloak的令牌接口获取有效令牌:

import requests
from django.urls import reverse
from rest_framework.test import APITestCase

class YourOIDCIntegrationTest(APITestCase):
    def test_api_with_valid_oidc_token(self):
        # 配置Keycloak令牌端点与客户端信息
        keycloak_token_endpoint = "http://你的Keycloak地址/realms/你的领域名/protocol/openid-connect/token"
        client_id = "你的Django客户端ID"
        client_secret = "你的Django客户端密钥"
        test_user = "预先在Keycloak创建的测试用户名"
        test_pwd = "测试用户密码"
        
        # 请求Keycloak获取访问令牌
        token_response = requests.post(
            keycloak_token_endpoint,
            data={
                "grant_type": "password",
                "client_id": client_id,
                "client_secret": client_secret,
                "username": test_user,
                "password": test_pwd,
            }
        )
        access_token = token_response.json().get("access_token")
        
        # 携带令牌发送API请求
        response = self.client.get(
            reverse("foo:bar"),
            HTTP_AUTHORIZATION=f"Bearer {access_token}"
        )
        
        # 验证请求成功
        self.assertEqual(response.status_code, 200)

关键配置说明

确保DRF的认证类已正确配置,在settings.py中添加:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'mozilla_django_oidc.contrib.drf.OIDCAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 15:42:50