使用API​​RequestFactory测试基于令牌的身份验证的正确方法是什么? [英] What's the proper way to test token-based auth using APIRequestFactory?

查看:96
本文介绍了使用API​​RequestFactory测试基于令牌的身份验证的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对我的终结点的查询工作正常(只要我向它传递一个有效的令牌),它就会返回我的响应数据的json表示形式.

The query to my endpoint works fine (as long as I pass it a valid token), it returns the json representation of my response data.

服务api中的代码调用我的终结点,并在标头中传递auth令牌:

The code in the service api that calls my endpoint, passing an auth token in the header:

headers = {'content-type': 'application/json',
           'Authorization': 'Token {}'.format(myToken)}
url = 'http://localhost:8000/my_endpoint/'
r = session.get(url=url, params=params, headers=headers)

在views.py中,我有一个方法装饰器,该装饰器将调度方法包装在视图上(viewsets.ReadOnlyModelViewSet):

In views.py, I have a method decorator that wraps the dispatch method on the view (viewsets.ReadOnlyModelViewSet):

def login_required(f):
    def check_login_and_call(request, *args, **kwargs):
        authentication = request.META.get('HTTP_AUTHORIZATION', b'')
        if isinstance(authentication, str):
            authentication = authentication.encode(HTTP_HEADER_ENCODING)
        key = authentication.split()
        if not key or len(key) != 2:
            raise PermissionDenied('Authentication failed.')
        user, token = authenticate_credentials(key[1])
        return f(request, *args, **kwargs)
    return check_login_and_call

我正在尝试编写测试以使用令牌对请求进行身份验证:

I'm trying to write a test to authenticate the request using a token:

from rest_framework.authtoken.models import Token
from rest_framework.test import APIRequestFactory
from rest_framework.test import APITestCase
from rest_framework.test import force_authenticate

class EndpointViewTest(APITestCase):
    def setUp(self):
        self.factory = APIRequestFactory()
        self.user = User.objects.create_user(
            username='user@foo.com', email='user@foo.com', password='top_secret')
        self.token = Token.objects.create(user=self.user)
        self.token.save()

    def test_token_auth(self):
        request = self.factory.get('/my_endpoint')
        force_authenticate(request, token=self.token.key)
        view = views.EndpointViewSet.as_view({'get': 'list'})
        response = view(request)
        self.assertEqual(response.status_code, 200)
        json_response = json.loads(response.render().content)['results']

由于某种原因,我无法获得正确通过此测试的令牌的请求.使用force_authenticate似乎并没有更改我用于验证令牌的标头.当前输出将引发"PermissionDenied:身份验证失败".因为未在请求中设置令牌.

For some reason, I cannot get the request to properly pass the token for this test. Using force_authenticate doesn't seem to change the header that I'm using for validating the token. The current output is raising "PermissionDenied: Authentication failed." because the token isn't being set on the request.

是否有适当的方法在测试的请求标头中进行设置或重构我最初使用它的方式?

Is there a proper way to set this in the request header in my test or to refactor the way I'm using it in the first place?

推荐答案

我找到了一种通过测试的方法,但是如果您对如何处理这些问题有更好的了解,请发表.

I found a way to get the test to pass, but please post if you have a better idea of how to handle any of this.

request = self.factory.get('/my_endpoint', HTTP_AUTHORIZATION='Token {}'.format(self.token))
force_authenticate(request, user=self.user)

更改了以上两行测试后,似乎可以根据令牌正确进行身份验证.

After changing the above two lines of the test, it seems to authenticate based on the token properly.

这篇关于使用API​​RequestFactory测试基于令牌的身份验证的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆