通过Django中的IP地址进行身份验证 [英] Authenticate by IP address in Django

查看:313
本文介绍了通过Django中的IP地址进行身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小的Django应用程序,其视图只限于某些用户.仅基于IP地址,来自特定网络的任何人都应该能够看到该视图而无需任何进一步的身份验证.该IP范围之外的其他任何人都应该被要求输入密码,并根据默认的Django用户管理进行身份验证.

I have a small Django application with a view that I want to restrict to certain users. Anyone from a specific network should be able to see that view without any further authentication, based on IP address alone. Anyone else from outside this IP range should be asked for a password and authenticated against the default Django user management.

我认为我必须为此编写一个自定义身份验证后端,但是文档使我感到困惑,因为authenticate()函数似乎期望使用用户名/密码组合或令牌.我不清楚在这里如何使用IP地址进行身份验证.

I assume I have to write a custom authentication backend for that, but the documentation confuses me as the authenticate() function seems to expect a username/password combination or a token. It is not clear to me how to authenticate using IP addresses here.

在Django中实现基于IP地址的身份验证的正确方法是什么?我宁愿为安全性相关的代码使用尽可能多的现有库函数,而不是自己编写所有库函数.

What would be the proper way to implement IP address-based authentication in Django? I'd prefer to use as much existing library functions as possible for security-related code instead of writing all of it myself.

推荐答案

有两种适用于这种身份验证的方法:

There are two suitable approaches for that kind of authentication:

  • 作为装饰器::如果某些视图(但不是很多)需要进行此检查,则最好为此编写一个装饰器(类似于@Jingo编写的东西)
  • 作为中间件::如果该检查需要由所有(或许多)视图完成,则可以使用
  • As Decorator: if some of views (but not many of them) requires this check, then it is better to write a decorator for that (something like @Jingo had written)
  • As Middleware: if that check needed to be done by all (or many) views, instead of using a decorator, writing a middleware is a better solution.

示例中间件可以是这样的:

A sample middleware can be something like:

ALLOWED_IP_BLOCKS = [......]

class NeedToLoginMiddleware(object):
    def process_request(self, request):
        ip = request.META['REMOTE_ADDR']
        if not ip in ALLOWED_IP_BLOCKS: #ip check
            if not request.user.is_authenticated(): #if ip check failed, make authentication check
                return HttpResponseRedirect(...)
        return None

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