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