2016-12-14 9 views
3

인증을 위해 Flask-HTTPAuth를 사용하고 있습니다. 요청이 인증되었는지 여부에 따라보기에서 다른 데이터를 표시하려고합니다. auth.login_required으로보기를 꾸미면 인증 된 사용자에게만 표시됩니다. 요청이 Flask-HTTPAuth로 인증되었는지 어떻게 테스트 할 수 있습니까?Flask-HTTPAuth가 뷰 내부에서 인증되는지 확인하십시오.

auth = HTTPBasicAuth() 

@app.route("/clothesInfo") 
@auth.login_required 
def show_info(): 
    return jsonify(blah blah blah) 
+1

당신이 사용자가 인증되면 정보가 포함되어 템플릿에 전달되는 객체가 필요 당신이 플라스크-httpauth이 할 수 있다면 나도 몰라 :

다음의 예는이 기술을 보여줍니다. 나는 분명히 [Flask-Login] (https://flask-login.readthedocs.io/en/latest/)으로 이것을 할 수 있음을 알고 있습니다. 여기를 참고하십시오 http://stackoverflow.com/questions/18361151/using-flask- login-session-with-jinja2-templates – MrLeeh

답변

3

원하는 것은 실제로 구현하기가 쉽습니다. verify_password 콜백에서 사용자가 자격 증명을 제공하지 않으면 사용자 이름과 암호가 ''으로 설정됩니다. 해당 기능에서 여전히 True을 반환 할 수 있으며 익명 사용자가 끝점에 액세스 할 수 있습니다.

auth = HTTPBasicAuth() 

@auth.verify_password 
def verify_password(username, password): 
    if username == '' or password == '': 
     # anonymous user, we still let them in 
     g.current_user = None 
     return True 
    g.current_user = my_verify_function(username, password) 
    return g.current_user is not None 

@app.route("/clothesInfo") 
@auth.login_required 
def show_info(): 
    if g.current_user: 
     # prepare data for authenticated users here 
     pass 
    else: 
     # prepare data for anonymous users here 
     pass 
    return jsonify(data) 
3

플라스크-HTTPAuth 유효한 인증을 제공 한 경우 바로 확인 할 수있는 방법이 없습니다, 당신은 (보기) 기능을 장식합니다. None을 반환하는 함수를 login_required으로 꾸밀 수 있습니다. 인증되지 않은 상태에서 호출하면 오류 응답이 반환되고 인증 된 경우 호출하면 None이 반환됩니다.

# a dummy callable to execute the login_required logic 
login_required_dummy_view = auth.login_required(lambda: None) 

def is_authenticated(): 
    try: 
     # default implementation returns a string error 
     return login_required_dummy_view() is None 
    except HTTPException: 
     # in case auth_error_callback raises a real error 
     return False 

@app.route('/info') 
def info(): 
    if is_authenticated(): 
     # logged in view 

    else: 
     # basic view 

Default login_required rather than adding decorator everywhere도 참조하십시오.

+0

안녕하세요, @ 데이비드. 내 대답을 보라. Flask-HTTP는 OP가 요구하는 것을 지원한다. verify 콜백은 클라이언트가'Authorization' 헤더를 보내지 않았을 때도 호출됩니다. 그래서 클라이언트를 허용 할 수 있습니다. – Miguel

+0

@Miguel oh duh, 그건 더 의미가 있습니다. – davidism