2

사용자를 인증하고 권한을 부여하기 위해 사용자 정의 인증 및 사용자 정의 미들웨어를 작성해야하는 경우가 있습니다. POST 요청에서 사용자 이름 암호 매개 변수를 확인하거나 토큰 기반 인증을 위해 쿠키가 설정되어 있는지 확인해야합니다. 자, 파이썬에서 함수 오버로딩이 허용되지 않는다는 것을 알았 으면, 어떻게하면 될까요? 맞춤 인증 및 맞춤 미들웨어에 대한 코드를 아래에 넣겠습니다.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 요청에서 사용자 이름과 암호를 확인하고 그대로 토큰 토큰 하나를 호출 할 때 문제는 짝수 저기, 어떻게 강제 할 수 있니?

쿠키를 삭제하고 다시 시도했지만 여전히 username과 password가있는 인증 기능을 params로 실행하지 않았습니다.

이 해결책은 무엇이 될 수 있습니까?

답변

5

파이썬은 함수 오버로딩을 지원하지 않습니다. 파이썬은 단순히 함수 오버로딩이 필요하지 않기 때문입니다. 귀하의 경우에는 두 번째 선언 인 authenticate이 첫 번째 선언을 덮어 쓰므로 토큰을 매개 변수로 사용하는 authenticate의 버전이 하나만 남습니다. 대신 무엇을해야

은 (그냥 예, 여러 가지 해결책이있다)이다 : 그것은 AuthMiddleWare 당신이 쓴 함께 작동합니다

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) 

이 방법.

+0

감사합니다 :) 할 것입니다. – Maverick

관련 문제