Python 如何使用Django oauth工具包使用Django rest框架测试API端点进行身份验证

Python 如何使用Django oauth工具包使用Django rest框架测试API端点进行身份验证,python,django,testing,oauth-2.0,django-rest-framework,Python,Django,Testing,Oauth 2.0,Django Rest Framework,我有一个Django rest framework视图集/路由器来定义API端点。视图集的定义如下: class DocumentViewSet(viewsets.ModelViewSet): permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope] model = Document 路由器定义为 router = DefaultRouter() router.register(r'do

我有一个Django rest framework视图集/路由器来定义API端点。视图集的定义如下:

class DocumentViewSet(viewsets.ModelViewSet):
    permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope]
    model = Document
路由器定义为

router = DefaultRouter()
router.register(r'documents', viewsets.DocumentViewSet)
使用url模式
url(r'^api/),包括(router.url))

通过获取正确的访问令牌并将其用于授权,我可以在浏览器/通过curl中很好地访问该端点。然而,目前还不清楚如何针对该端点编写测试

以下是我尝试过的:

class DocumentAPITests(APITestCase):
    def test_get_all_documents(self):
        user = User.objects.create_user('test', 'test@test.com', 'test')
        client = APIClient()
        client.credentials(username="test", password="test")
        response = client.get("/api/documents/")
        self.assertEqual(response.status_code, 200) 

此操作失败,来自
客户端.get()调用的HTTP 401响应失败。使用django oauth toolkit for oauth2 authentication在DRF中测试API端点的正确方法是什么?

编写测试时,应将未测试的内容从测试本身中提取出来,通常将任何设置代码放在测试的
setup
方法中。在使用OAuth进行API测试的情况下,这通常包括测试用户、OAuth应用程序和活动访问令牌

对于
django oauth toolkit
,以及其他django应用程序,我始终推荐使用。这允许您避免进行不必要的API调用,特别是对于OAuth这样的多部分流程,并且只创建所需的少数模型对象

def setUp(self):
    self.test_user = UserModel.objects.create_user("test_user", "test@user.com", "123456")

    self.application = Application(
        name="Test Application",
        redirect_uris="http://localhost",
        user=self.test_user,
        client_type=Application.CLIENT_CONFIDENTIAL,
        authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE,
    )
    self.application.save()

def test_revoke_access_token(self):
    from datetime import datetime
    from django.utils import timezone

    tok = AccessToken.objects.create(
        user=self.test_user, token='1234567890',
        application=self.application, scope='read write',
        expires=timezone.now() + datetime.timedelta(days=1)
    )

从这里开始,您只需要使用已生成的令牌进行身份验证。您可以通过Django REST框架或由Django REST框架提供来实现这一点。

我对OAuth2使用了相同的库

这对我有用

from oauth2_provider.settings import oauth2_settings
from oauth2_provider.models import get_access_token_model, 
get_application_model
from django.contrib.auth import get_user_model
from django.utils import timezone
from rest_framework.test import APITestCase

Application = get_application_model()
AccessToken = get_access_token_model()
UserModel = get_user_model()

class Test_mytest(APITestCase):

    def setUp(self):

        oauth2_settings._SCOPES = ["read", "write", "scope1", "scope2", "resource1"]

        self.test_user = UserModel.objects.create_user("test_user", "test@example.com", "123456")

        self.application = Application.objects.create(
                                                name="Test Application",
                                                redirect_uris="http://localhost http://example.com http://example.org",
                                                user=self.test_user,
                                                client_type=Application.CLIENT_CONFIDENTIAL,
                                                authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE,
                                            )

        self.access_token = AccessToken.objects.create(
                                                    user=self.test_user,
                                                    scope="read write",
                                                    expires=timezone.now() + timezone.timedelta(seconds=300),
                                                    token="secret-access-token-key",
                                                    application=self.application
                                                )
        # read or write as per your choice
        self.access_token.scope = "read"
        self.access_token.save()

        # correct token and correct scope
        self.auth =  "Bearer {0}".format(self.access_token.token)

    def test_success_response(self):

        url = reverse('my_url',)

        # Obtaining the POST response for the input data
        response = self.client.get(url, HTTP_AUTHORIZATION=self.auth)

        # checking wether the response is success
        self.assertEqual(response.status_code, status.HTTP_200_OK)
现在一切都会按预期进行。
希望这有帮助。谢谢,这是票。我错过了访问令牌的创建过程+不清楚如何将令牌注入到请求中。谢谢这正是我要找的。非常感谢你!