2

我处于需要进行身份验证和自定义中间件来验证和授权用户的情况。我必须在POST请求中设置用户名密码参数,或者设置cookie或者不设置基于令牌的认证。现在,据我所知,Python中不允许使用函数重载,我怎么能实现它。我将下面的代码放在自定义身份验证和自定义中间件中。django自定义身份验证后端与自定义中间件(包括用户名,密码和令牌取消身份验证)

定制中间件:

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并再次尝试,但仍然没有启用带有用户名和密码作为参数的认证功能。

有什么可以解决这个请吗?

回答

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你写的工作。

+0

谢谢:)它会。 – Maverick 2013-05-13 10:10:42