Python Forum

Full Version: Prompt of Access ( Authentication Http ) ?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm doing some authentication tests through the http header, but the browser's login prompt window isn't being triggered? I think I'm forgetting something, below is the example:

from wsgiref.simple_server import make_server
 
 
def app(environ, start_response):
 
    status = "401 Unauthorized"
    headers = [
        ("Content-type", "text/plain; charset=utf-8"),
        ("WWW-Authenticate:", "Basic realm=Access to the internal site")
    ] 
    start_response(status, headers)
 
    # The returned object is going to be printed
    return [b"401 Unauthorized"]
 
with make_server("", 8000, app) as httpd:
    print("Serving on port 8000...")
 
    # Serve until process is killed
    httpd.serve_forever()
This is a stab in the dark, but it's possible there may be something here that can help.
I checked the link, but nothing related to schema type and realm as is in the statement below that triggers the window prompt for http authentication:

(Dec-07-2022, 10:27 PM)JohnnyCoffee Wrote: [ -> ]("WWW-Authenticate:", "Basic realm=Access to the internal site")
The colon at the end of WWW-Authenticate is wrong.
But you also require handling:
  • Not Authorized
  • Authorized
  • Incorrect authorization

Code to handle this:
from base64 import b64decode
from hashlib import sha256
from wsgiref.simple_server import make_server

CREDENTIALS = ["fb44d98b9d56bbe49028eacc8574f5715178e6d3470d276a1697de3df68e7579"]
HEADER_AUTH = [
    ("Content-type", "text/plain; charset=utf-8"),
    ("WWW-Authenticate", "Basic realm=Access to the internal site"),
]
HEADER_NORMAL = [HEADER_AUTH[0]]
HTTP401 = "401 Unauthorized"


def app(environ, start_response):

    auth = environ.get("HTTP_AUTHORIZATION", "")

    if not auth.startswith("Basic"):
        start_response(HTTP401, HEADER_AUTH)
        return [b"401 Unauthorized"]

    username, password = b64decode(auth.split()[-1]).split(b":")

    if sha256(username + password).hexdigest() in CREDENTIALS:
        start_response("200 Ok", HEADER_NORMAL)
        return [b"200 Ok"]
    else:
        start_response(HTTP401, HEADER_AUTH)
        return [b"401 Unauthorized"]


with make_server("", 8000, app) as httpd:
    print("Serving on port 8000...")
    httpd.serve_forever()
You won't use this in production. There is a middleware for HTTPBasicAuth.
https://github.com/mvantellingen/wsgi-basic-auth
- double post