Skip to content

Instantly share code, notes, and snippets.

@jasco
Created October 15, 2015 18:25
Show Gist options
  • Save jasco/02352d91e52bc7ece570 to your computer and use it in GitHub Desktop.
Save jasco/02352d91e52bc7ece570 to your computer and use it in GitHub Desktop.
Using Flask auth to authorize access to apache static resources

Using Apache auth with Flask user authentication

Flask supported user authentication combined with direct apache basic authentication for static files

Flask Auth

The flask-security module uses flask-login to authenticate users and stores a token identifying the user in a session cookie encrypted using an application secret the prevents forgery. Additional modules can be used to store session tokens only on the server if desired.

The flask application is designed to check user or role membership for urls that need authorization.

Apache Auth

Apache can be used with many different mod_auth* modules that allow Apache to request credentials from the user and verify them via different mechanisms.

mod_auth_basic sends the user and password in the request headers that the module checks on each request. The browser caches the credentials after entry and automatically includes them when sending requests to the same domain and auth realm.

mod_auth_form is similar to auth_basic but it allows the credentials to be submitted via an http POST with parameters httpd_username and httpd_password rather than the typical browser managed query mechanism.

mod_session allows the server write a cookie that contains a username and password that can be used to with the auth modules instead of the typical plaintext username and password header values. Add mod_session_crypto to encrypt the session cookie so the username and password is not easily accessible. When configured the cookie name, secret used to encrypt/decrypt/authenticate the cookie, as well as whether the cookie is httponly or secure.

Apache mod_wsgi includes infrastructure to delegate mod_auth* approval to a plugin wsgi script. Reference mod_wsgi Access Control Mechanisms

WSGIAuthGroupScript /usr/local/wsgi/scripts/auth.wsgi
def groups_for_user(environ, user):
    if user == 'user1':
        return ['members']
    return ['']

WSGIAccessScript /usr/local/wsgi/script/access.wsgi

def allow_access(environ, host):
    return host in ['localhost', '::1']

WSGIAuthUserScript /usr/local/wsgi/scripts/auth.wsgi

def check_password(environ, user, password):
    if user == 'user1':
        if password == 'secret':
            return True
        return False
    return None

Combined

On flask auth, after authenticating the user and registering the login with flask-login the flask session is created. Then an internal flask to apache request is made to the session creation endpoint. The returned apache session cookie is forwarded to the client

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment