2

我处于需要进行自定义身份验证和自定义中间件来对用户进行身份验证和授权的情况。我必须检查 POST 请求中的用户名密码参数,或者是否为基于令牌的身份验证设置了 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

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

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

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

4

1 回答 1

5

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

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

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您编写的内容一起使用。

于 2013-05-10T15:20:41.977 回答