2010-11-26 58 views
10

我被困在試圖讓基於python的web服務器工作。使用BaseHTTP進行基本身份驗證的Python HTTP服務器卡住

我想做基本身份驗證(發送一個401頭)和對用戶列表進行身份驗證。使用「WWW-Authorize」標題發送401響應沒有問題,我可以驗證用戶的響應(base64編碼的用戶名&密碼),但登錄框在驗證成功後會彈出。

import SimpleHTTPServer 
import SocketServer 
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer 

class Handler(BaseHTTPRequestHandler): 
    ''' Main class to present webpages and authentication. ''' 
    def do_HEAD(self): 
     print "send header" 
     self.send_response(401) 
     self.send_header('WWW-Authenticate', 'Basic realm=\"Test\"') 
     self.send_header('Content-type', 'text/html') 
     self.end_headers() 

    def do_GET(self): 
     ''' Present frontpage with user authentication. ''' 
     self.do_HEAD() 

     if self.headers.getheader('Authorization') == None: 
      self.wfile.write('no auth header received') 
      pass 
     elif self.headers.getheader('Authorization') == 'Basic dGVzdDp0ZXN0': 
      self.wfile.write(self.headers.getheader('Authorization')) 
      self.wfile.write('authenticated!') 
      pass 
     else: 
      self.wfile.write(self.headers.getheader('Authorization')) 
      self.wfile.write('not authenticated') 
      pass 

httpd = SocketServer.TCPServer(("", 10001), Handler) 

httpd.serve_forever() 

if __name__ == '__main__': 
    main() 

在第一負載(HTTP://本地主機:10001)的loginbox彈出,我進入測試,測試(正確的用戶)用戶通過驗證確定,但框彈出備份,如果我點擊取消,我到達驗證頁面...

任何人都可以在這裏幫忙嗎?我懷疑它與授權在do_GET下發生的事實有關,do_GET每次頁面加載時都會觸發。

回答

6

這是因爲您無條件發送401和WWW-Authenticate標題作爲迴應。只有在請求中沒有可接受的身份驗證憑證時才需要執行此操作。如果您對請求感到滿意,請發送200(或其他適當的信息),並且不要再次請求認證。

17

試試這個尺寸爲:

import SimpleHTTPServer 
import SocketServer 
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer 

class Handler(BaseHTTPRequestHandler): 
    ''' Main class to present webpages and authentication. ''' 
    def do_HEAD(self): 
     print "send header" 
     self.send_response(200) 
     self.send_header('Content-type', 'text/html') 
     self.end_headers() 

    def do_AUTHHEAD(self): 
     print "send header" 
     self.send_response(401) 
     self.send_header('WWW-Authenticate', 'Basic realm=\"Test\"') 
     self.send_header('Content-type', 'text/html') 
     self.end_headers() 

    def do_GET(self): 
     ''' Present frontpage with user authentication. ''' 
     if self.headers.getheader('Authorization') == None: 
      self.do_AUTHHEAD() 
      self.wfile.write('no auth header received') 
      pass 
     elif self.headers.getheader('Authorization') == 'Basic dGVzdDp0ZXN0': 
      self.do_HEAD() 
      self.wfile.write(self.headers.getheader('Authorization')) 
      self.wfile.write('authenticated!') 
      pass 
     else: 
      self.do_AUTHHEAD() 
      self.wfile.write(self.headers.getheader('Authorization')) 
      self.wfile.write('not authenticated') 
      pass 

httpd = SocketServer.TCPServer(("", 10001), Handler) 

httpd.serve_forever() 

if __name__ == '__main__': 
    main() 
+0

輝煌!很好,很簡單 – Claudiu 2013-03-08 23:24:46

相關問題