2016-12-14 35 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

Flask-HTTPAuth没有办法检查是否提供了有效的认证,你必须修饰(视图)函数。您可以装饰一个返回Nonelogin_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

嘿,@davidism。看到我的答案,Flask-HTTP确实支持OP要求的内容。当客户端没有发送'Authorization'头时,验证回调也会被调用,因此您可以选择允许客户端进入。 – Miguel

+0

@Miguel oh duh,这样做更有意义。 – davidism

相关问题