Download flask-ldap3-login Documentation and more Exercises Network Programming in PDF only on Docsity!
flask-ldap3-login Documentation
Release 0.0.0.dev
Nick Whyte
Nov 09, 2018
ii
Flask LDAP3 Login allows you to easily integrate your flask app with an LDAP directory. It can be used as an
extension to Flask-Login and can even be used with Flask-Principal for permission and privilege management.
Flask LDAP3 Login uses the ldap3 library, maintaining compatability with python 3.4 and backwards.
Flask LDAP3 Login Will:
- Allow you to query whether or not a user’s credentials are correct
- Query the directory for users details
- Query the directory for group details
- Query the directory for users group memberships
- Provide a contextual ldap_manager.connection object (ldap3.Connection) which can be
used in any flask request context. Useful for writing your own more advanced queries.
Flask LDAP3 Login Wont:
- Provide a login/logout mechanism. You need to provide this with something like flask-login
- Provide any extension to the application’s session. User tracking and group tracking should be done via
flask-login and flask-principal
View the Full Documentation at ReadTheDocs
Contents 1
CHAPTER 1
Contents:
1.1 Configuration
The following configuration values are used by Flask-LDAP3-Login:
4 Chapter 1. Contents:
1.1.2 Filters/Searching
LDAP_USER_SEARCH_SCOPE Specifies what scope to search in when searching for a spe-
cific user. Defaults to 'LEVEL', which limits search results
to objects in the root of your search base. Use 'SUBTREE'
to do a recursive search within the search base.
LDAP_USER_OBJECT_FILTER Specifies what object filter to apply when searching for users.
Defaults to '(objectclass=person)'
LDAP_USER_LOGIN_ATTR Declares what ldap attribute corresponds to the username
passed to any login method when performing a bind. De-
faults to 'uid'
LDAP_USER_RDN_ATTR Specifies the RDN attribute used in the directory. Defaults to
'uid'
LDAP_GET_USER_ATTRIBUTES Specifies which LDAP attributes to get when search-
ing LDAP for a user/users. Defaults to ldap3.
ALL_ATTRIBUTES
LDAP_GROUP_SEARCH_SCOPE Specifies what scope to search in when searching for a spe-
cific group. Defaults to 'LEVEL', which limits search
results to objects in the root of your search base. Use
'SUBTREE' to do a recursive search within the search base.
LDAP_GROUP_OBJECT_FILTER Specifies what object filter to apply when searching for
groups. Defaults to '(objectclass=group)'
LDAP_GROUP_MEMBERS_ATTR Specifies the LDAP attribute where group members are de-
clared. Defaults to 'uniqueMember'
LDAP_GET_GROUP_ATTRIBUTES Specifies which LDAP attributes to get when search-
ing LDAP for a group/groups. Defaults to ldap3.
ALL_ATTRIBUTES
1.2 Quick Start
1.2.1 Install the Package
$ pip install flask-ldap3-login
1.2.2 Basic Application
This is a basic application which uses Flask-Login to handle user sessions. The application stores the users in the
dictionary users.
from flask import Flask, url_for from flask_ldap3_login import LDAP3LoginManager from flask_login import LoginManager, login_user, UserMixin, current_user from flask import render_template_string, redirect from flask_ldap3_login.forms import LDAPLoginForm
app = Flask(name) app.config['SECRET_KEY'] = 'secret' app.config['DEBUG'] = True
(continues on next page)
6 Chapter 1. Contents:
(continued from previous page)
Setup LDAP Configuration Variables. Change these to your own settings.
All configuration directives can be found in the documentation.
Hostname of your LDAP Server
app.config['LDAP_HOST'] = 'ad.mydomain.com'
Base DN of your directory
app.config['LDAP_BASE_DN'] = 'dc=mydomain,dc=com'
Users DN to be prepended to the Base DN
app.config['LDAP_USER_DN'] = 'ou=users'
Groups DN to be prepended to the Base DN
app.config['LDAP_GROUP_DN'] = 'ou=groups'
The RDN attribute for your user schema on LDAP
app.config['LDAP_USER_RDN_ATTR'] = 'cn'
The Attribute you want users to authenticate to LDAP with.
app.config['LDAP_USER_LOGIN_ATTR'] = 'mail'
The Username to bind to LDAP with
app.config['LDAP_BIND_USER_DN'] = None
The Password to bind to LDAP with
app.config['LDAP_BIND_USER_PASSWORD'] = None
login_manager = LoginManager(app) # Setup a Flask-Login Manager ldap_manager = LDAP3LoginManager(app) # Setup a LDAP3 Login Manager.
Create a dictionary to store the users in when they authenticate
This example stores users in memory.
users = {}
Declare an Object Model for the user, and make it comply with the
flask-login UserMixin mixin.
class User (UserMixin): def init(self, dn, username, data): self.dn = dn self.username = username self.data = data
def repr(self): return self.dn
def get_id(self): return self.dn
Declare a User Loader for Flask-Login.
Simply returns the User if it exists in our 'database', otherwise
returns None.
@login_manager .user_loader def load_user(id): if id in users: return users[id] (continues on next page)
1.2. Quick Start 7
(continued from previous page)
Successfully logged in, We can now access the saved user object
via form.user.
login_user(form.user) # Tell flask-login to log them in. return redirect('/') # Send them home
return render_template_string(template, form=form)
if name == 'main': app.run()
1.2.3 Basic Scripting Usage (Without a Flask App)
This is an example for if you wish to simply use the module, maybe for testing or for use in some other environment.
from flask_ldap3_login import LDAP3LoginManager
config = dict()
Setup LDAP Configuration Variables. Change these to your own settings.
All configuration directives can be found in the documentation.
Hostname of your LDAP Server
config['LDAP_HOST'] = 'ad.mydomain.com'
Base DN of your directory
config['LDAP_BASE_DN'] = 'dc=mydomain,dc=com'
Users DN to be prepended to the Base DN
config['LDAP_USER_DN'] = 'ou=users'
Groups DN to be prepended to the Base DN
config['LDAP_GROUP_DN'] = 'ou=groups'
The RDN attribute for your user schema on LDAP
config['LDAP_USER_RDN_ATTR'] = 'cn'
The Attribute you want users to authenticate to LDAP with.
config['LDAP_USER_LOGIN_ATTR'] = 'mail'
The Username to bind to LDAP with
config['LDAP_BIND_USER_DN'] = None
The Password to bind to LDAP with
config['LDAP_BIND_USER_PASSWORD'] = None
Setup a LDAP3 Login Manager.
ldap_manager = LDAP3LoginManager()
Init the mamager with the config since we aren't using an app
ldap_manager.init_config(config)
Check if the credentials are correct
response = ldap_manager.authenticate('username', 'password') (continues on next page)
1.2. Quick Start 9
(continued from previous page)
print(response.status)
1.2.4 Custom TLS Context
This is an example that shows how to initialize a custom TLS context for securing communication between the module
and a secure LDAP (LDAPS server.
from flask_ldap3_login import LDAP3LoginManager from ldap3 import Tls import ssl
config = dict()
Setup LDAP Configuration Variables. Change these to your own settings.
All configuration directives can be found in the documentation.
Hostname of your LDAP Server
config['LDAP_HOST'] = 'ad.mydomain.com'
Port number of your LDAP server
config['LDAP_PORT'] = 636
Base DN of your directory
config['LDAP_BASE_DN'] = 'dc=mydomain,dc=com'
Users DN to be prepended to the Base DN
config['LDAP_USER_DN'] = 'ou=users'
Groups DN to be prepended to the Base DN
config['LDAP_GROUP_DN'] = 'ou=groups'
The RDN attribute for your user schema on LDAP
config['LDAP_USER_RDN_ATTR'] = 'cn'
The Attribute you want users to authenticate to LDAP with.
config['LDAP_USER_LOGIN_ATTR'] = 'mail'
The Username to bind to LDAP with
config['LDAP_BIND_USER_DN'] = None
The Password to bind to LDAP with
config['LDAP_BIND_USER_PASSWORD'] = None
Specify the server connection should use SSL
config['LDAP_USE_SSL'] = True
Instruct Flask-LDAP3-Login to not automatically add the server
config['LDAP_ADD_SERVER'] = False
Setup a LDAP3 Login Manager.
ldap_manager = LDAP3LoginManager()
Init the mamager with the config since we aren't using an app
ldap_manager.init_config(config) (continues on next page)
10 Chapter 1. Contents:
authenticate (username, password)
An abstracted authentication method. Decides whether to perform a direct bind or a search bind based
upon the login attribute configured in the config.
Args: username (str): Username of the user to bind password (str): User’s password to bind with.
Returns: AuthenticationResponse
authenticate_direct_bind (username, password)
Performs a direct bind. We can do this since the RDN is the same as the login attribute. Hence we just
string together a dn to find this user with.
Args:
username (str): Username of the user to bind (the field specified as LDAP_BIND_RDN_ATTR)
password (str): User’s password to bind with.
Returns: AuthenticationResponse
authenticate_direct_credentials (username, password)
Performs a direct bind, however using direct credentials. Can be used if interfacing with an Active Direc-
tory domain controller which authenticates using username@domain.com directly.
Performing this kind of lookup limits the information we can get from ldap. Instead we can only deduce
whether or not their bind was successful. Do not use this method if you require more user info.
Args:
username (str): Username for the user to bind with. LDAP_BIND_DIRECT_PREFIX will be
prepended and LDAP_BIND_DIRECT_SUFFIX will be appended.
password (str): User’s password to bind with.
Returns: AuthenticationResponse
authenticate_search_bind (username, password)
Performs a search bind to authenticate a user. This is required when a the login attribute is not the same as
the RDN, since we cannot string together their DN on the fly, instead we have to find it in the LDAP, then
attempt to bind with their credentials.
Args:
username (str): Username of the user to bind (the field specified as
LDAP_BIND_LOGIN_ATTR)
password (str): User’s password to bind with when we find their dn.
Returns: AuthenticationResponse
compiled_sub_dn (prepend)
Returns: str: A DN with the DN Base appended to the end.
Args: prepend (str): The dn to prepend to the base.
connection
Convenience property for externally accessing an authenticated connection to the server. This connection
is automatically handled by the appcontext, so you do not have to perform an unbind.
Returns: ldap3.Connection: A bound ldap3.Connection
Raises:
ldap3.core.exceptions.LDAPException: Since this method is performing a bind on behalf of the
caller. You should handle this case occuring, such as invalid service credentials.
12 Chapter 1. Contents:
destroy_connection (connection)
Destroys a connection. Removes the connection from the appcontext, and unbinds it.
Args: connection (ldap3.Connection): The connnection to destroy
full_group_search_dn
Returns a the base search DN with the group search DN prepended.
Returns: str: Full group search dn
full_user_search_dn
Returns a the base search DN with the user search DN prepended.
Returns: str: Full user search dn
get_group_info (dn, _connection=None)
Gets info about a group specified at dn.
Args: dn (str): The dn of the group to find _connection (ldap3.Connection): A connection object to use
when
searching. If not given, a temporary connection will be created, and destroyed after use.
Returns: dict: A dictionary of the group info from LDAP
get_object (dn, filter, attributes, _connection=None)
Gets an object at the specified dn and returns it.
Args: dn (str): The dn of the object to find. filter (str): The LDAP syntax search filter. attributes (list): A
list of LDAP attributes to get when searching. _connection (ldap3.Connection): A connection object
to use when
searching. If not given, a temporary connection will be created, and destroyed after use.
Returns: dict: A dictionary of the object info from LDAP
get_user_groups (dn, group_search_dn=None, _connection=None)
Gets a list of groups a user at dn is a member of
Args: dn (str): The dn of the user to find memberships for. _connection (ldap3.Connection): A connection
object to use when
searching. If not given, a temporary connection will be created, and destroyed after use.
group_search_dn (str): The search dn for groups. Defaults to '{LDAP_GROUP_DN},
{LDAP_BASE_DN}'.
Returns: list: A list of LDAP groups the user is a member of.
get_user_info (dn, _connection=None)
Gets info about a user specified at dn.
Args: dn (str): The dn of the user to find _connection (ldap3.Connection): A connection object to use
when
searching. If not given, a temporary connection will be created, and destroyed after use.
Returns: dict: A dictionary of the user info from LDAP
get_user_info_for_username (username, _connection=None)
Gets info about a user at a specified username by searching the Users DN. Username attribute is the same
as specified as LDAP_USER_LOGIN_ATTR.
Args: username (str): Username of the user to search for. _connection (ldap3.Connection): A connection
object to use when
1.3. API 13
validate (*args, **kwargs)
Validates the form by calling validate on each field, passing any extra Form.validate_ valida-
tors to the field validator.
also calls validate_ldap
exception flask_ldap3_login.forms. LDAPValidationError (message=”, *args,
**kwargs)
1.3. API 15
16 Chapter 1. Contents: