django自定义身份验证后端与自定义中间件(用户名,密码和基于令牌的身份验证)

时间:2013-05-10 13:10:37

标签: python django python-2.7 django-authentication django-middleware

我处于需要制作自定义身份验证和自定义中间件以对用户进行身份验证和授权的情况。我必须在POST请求中设置用户名密码params,或者是否设置了cookie用于基于令牌的身份验证。现在,我知道python中不允许函数重载,我怎么能实现它。我将下面的代码放在自定义身份验证和自定义中间件上。

自定义中间件:

from django.contrib.auth import authenticate

class AuthMiddleWare(object):
    def process_request(self, request):

        if request.path != '/favicon.ico':
            print "inside process_request " + request.path              

            if request.method == 'POST' and request.POST.has_key('username' ) and request.POST.has_key('password'):                     
                authenticate(username = request.POST.get('username'),password = request.POST.get('password'))

            if 'SPRING_SECURITY_REMEMBER_ME_COOKIE' in request.COOKIES:                     
                authenticate(token = request.COOKIES.get('SPRING_SECURITY_REMEMBER_ME_COOKIE'))

        return None

自定义身份验证后端:

from core.api import NcpAPI       

class CustomNCPAuthBackend(object):     
    """
    This is custom authentication backend.
    Authenticate against the webservices call.

    The method below would override authenticate() of django.contrib.auth    
    """
    def authenticate(self, username = None, password = None):           
        print "inside authenticate of username and password with username being : "+username            
        return None

    def authenticate(self,token=None):
        print "inside authenticate of token with token being : "+token
        return None

问题是,即使我在post请求中检查用户名和密码,它也会在令牌中调用令牌,但是我怎么能以某种方式强制它呢?

我尝试删除cookie并再次尝试但仍然不会使用用户名和密码作为参数启动身份验证功能。

有什么可以解决这个问题?

1 个答案:

答案 0 :(得分:5)

你是对的,Python不支持函数重载,因为它根本不需要它。在你的情况下会发生的是authenticate的第二个声明会覆盖第一个声明,所以你只剩下一个版本的authenticate,一个以令牌作为参数的版本。

你应该做的是(只是一个例子,有很多可能的解决方案):

class CustomNCPAuthBackend(object):
    """
    This is custom authentication backend.
    Authenticate against the webservices call.

    The method below would override authenticate() of django.contrib.auth    
    """
    def authenticate_password(self, username=None, password=None):
        print "inside authenticate of username and password with username being : "+username
        return None

    def authenticate_token(self,token=None):
        print "inside authenticate of token with token being : "+token
        return None

    def authenticate(self, token=None, username=None, password=None):
        if token is not None:
             return self.authenticate_token(token)
        else:
             return self.authenticate_password(username, password)

这样它就可以与你写的AuthMiddleWare一起使用。