来自同一服务器的TastyPie身份验证

时间:2014-02-11 16:57:45

标签: python django tastypie

我在TastyPie中有一个API,它在同一个域上使用。我只想允许来自我的服务器的请求。

TastyPie有许多不同的身份验证选项,但是我无法使用会话身份验证,因为没有人登录, API密钥可能是在我的剧本中查看。

所以我想我可以用 Django csrf令牌以某种方式验证帖子。这可能是任何例子(我搜索过)还是我错过了一个选项?

1 个答案:

答案 0 :(得分:2)

This answer提供了以下获取请求IP地址的方法:

def get_client_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip

您可以尝试将其与自定义Authentication类耦合,如下所示:

class IpAuthentication(Authentication):
    def is_authenticated(self, request, **kwargs):
        return get_client_ip(request) in SETTINGS.ALLOWED_IPS:

您必须填写自己的SETTINGS.ALLOWED_IPS列表。然而,这是not a foolproof method,因为IP地址可以伪造。