miguelgrinberg / Flask-HTTPAuth

Simple extension that provides Basic, Digest and Token HTTP authentication for Flask routes
MIT License
1.27k stars 228 forks source link

Add check before asking for credentials #165

Closed OpenSourceSimon closed 1 month ago

OpenSourceSimon commented 1 month ago

Hi 👋 , I just discovered this project and it's perfect for what I need! However, I want to check the IP address of my users first before asking them to authenticate. For example, if I'm visiting from my home IP address, I don't want to enter a username and password. Is it possible to add a function before asking for authentication?

Thanks in advance for your reply!

miguelgrinberg commented 1 month ago

The function that checks authentication credentials is provided by your application, you can do whatever you want in there to allow a user in. For example:

@auth.verify_password
def verify_password(username, password):
    if request.remote_addr == MY_IP_ADDRESS:
        return "miguel"  # <--- ignore credentials and let myself in directly
    if username in users and \
            check_password_hash(users.get(username), password):
        return username
OpenSourceSimon commented 1 month ago

Thanks for your reply! I also managed it to do it by creating a custom decorator:



# Custom authentication decorator to check IPs before applying HTTP Digest Authentication
def http_auth(func):
    def wrapper(*args, **kwargs):
        ip = request.headers.get("X-Forwarded-For")
        if not ip:
            ip = request.remote_addr

        ip_addresses = fetch_ip_addresses()

        if ip in ip_addresses:
            return func(*args, **kwargs)
        return auth.login_required(func)(*args, **kwargs)
    return wrapper
miguelgrinberg commented 1 month ago

The disadvantage with your solution is that you cannot call auth.current_user() to know who the user is. My solution would allow this, even when the user was let in through the IP check.

OpenSourceSimon commented 1 month ago

The disadvantage with your solution is that you cannot call auth.current_user() to know who the user is. My solution would allow this, even when the user was let in through the IP check.

You're right, however for my particular use-case it isn't necessary to access the user. I'm using Flask-Security too which handles the authentication, the HTTP Auth is just an extra step for unkown IPs.