2015-04-19 118 views
2

我正在運行Flask網絡應用程序並使用Apache基本身份驗證(使用.htaccess和.htpasswd文件)來密碼保護它。我想密碼只保護應用程序中的一個網頁。當我用密碼保護網頁的html文件時,沒有任何效果,網頁仍然沒有密碼保護。難道這是因爲它是我的python文件使用render_template調用html文件?我不知道如何解決這個問題。密碼保護Flask應用程序中的一個網頁

+0

你是什麼意思「密碼保護html文件」? – dirn

+0

我的意思是我添加了.htaccess和.htpasswd文件,並在.htaccess文件中指定了html文件。訪問文件時,這些文件應詢問用戶名和密碼。 – accelke

+0

這隻有在您通過Apache直接提供HTML文件時纔有效。您需要限制對Flask中端點的訪問。 – dirn

回答

8

您需要限制對端點的訪問。 This snippet應該讓你開始正確的道路。

from functools import wraps 
from flask import request, Response 


def check_auth(username, password): 
    """This function is called to check if a username/
    password combination is valid. 
    """ 
    return username == 'admin' and password == 'secret' 

def authenticate(): 
    """Sends a 401 response that enables basic auth""" 
    return Response(
    'Could not verify your access level for that URL.\n' 
    'You have to login with proper credentials', 401, 
    {'WWW-Authenticate': 'Basic realm="Login Required"'}) 

def requires_auth(f): 
    @wraps(f) 
    def decorated(*args, **kwargs): 
     auth = request.authorization 
     if not auth or not check_auth(auth.username, auth.password): 
      return authenticate() 
     return f(*args, **kwargs) 
    return decorated 

有了這個,你可以裝飾你想要@requires_auth限制任何端點。

@app.route('/secret-page') 
@requires_auth 
def secret_page(): 
    return render_template('secret_page.html') 
+0

我實際上使用的是類似於以前的方法。我用這種方法的問題是,當我輸入用戶名和密碼時,它只是再次提示他們,它永遠不會驗證。 – accelke

+0

從片段:如果您使用mod_wsgi進行基本身份驗證,則必須啓用身份驗證轉發,否則apache將使用所需的頭文件並且不會將其發送到您的應用程序:[WSGIPassAuthorization](https://code.google.com/ p/modwsgi /維基/ ConfigurationDirectives#WSGIPassAuthorization)。 – dirn

+0

是的,我確實在我的/etc/apache2/sites-available/app.com.conf文件中添加了「WSGIPassAuthorization On」,但它沒有任何區別。是否有其他文件需要放入? – accelke