Handle 401 and 403 in WSGI/Python

371 Views Asked by At

I have created started a WSGI server using make_sever method of wsgiref.simple_server in Python. Below is the code for starting the server.

port = 5000
httpd = make_server("localhost", port, Request_Handler)
print "Started Sever on port", str(port)
try :
    httpd.serve_forever()
except KeyboardInterrupt :
    print "Server Closed"

And this is my Request_Handler Function

def Request_Handler(environ, start_response):
count = 0
if environ["PATH_INFO"] == "/" :
    response_body = "No authentication required on root page"
    status = "200 OK"
    response_headers = [('Content-Type', 'text/plain'),
                        ('Content-Length', str(len(response_body)))]
    start_response(status, response_headers)
    return [response_body]

elif environ["PATH_INFO"] == '/AM-PM' :
    if authentication(environ.get('HTTP_AUTHORIZATION')) :
        print "Structure of HTTP_AUTHORIZATION IS :"
        print environ.get("HTTP_AUTHORIZATION")
        start_response('200 OK', [('Content-Type', 'text/plain')])
        return ["Authentication valid"]
    else :
        start_response('401 Unauthorized',
                       [('Content-Type', 'text/html'),
                       ('WWW-Authenticate', 'Basic realm="Login"')])
        count = count + 1
        return ["Please Try Again"]
        if count == 3:
            start_response('403 FORBIDDEN', [('Content-Type', 'text/plain'),('WWW-Authenticate', 'Basic realm="Login"')])
            return ["Authentication is invalid"]

Earlier, in the else block I used only the 401 response and it was working fine. Whenever someone entered a wrong password. I asked again for the username and password. However now I wanted that after 3 number of trails. 403 response is started and return Authentication is invalid.

I thought of using a count variable to count the number of invalid request and once it is incremented to 3 a 403 response will start.

However, when I used this code, No user-name and password is asked, instead 200 response is started with a print message of Authentication is Valid which is not what I wanted.

Any Suggestions where I am going wrong

PS this is the authentication Function I used

def authentication(header) :
if not header :
    return False
scheme, data = header.split(None, 1)
print "Scheme : ", scheme
print "Data : ", data
decoded = b64decode(data).decode('UTF-8')
print "Decoded : ", decoded
username, password = decoded.split(':', 1)
return username == password #True Statement 200 response will be started.
0

There are 0 best solutions below