Fastapi authentication domain controller
Configure a fastapi application to authenticate against a domain controller
For creating internal tools in companies, as I do on a monthly basis, I am deeply in love with the fact that it is possible to hide my important applications from outside eyes unless you have a valid company login. Active Directory is the standard authentication service for most people in companies, as your employee credentials are tied to services such as Outlook and Microsoft 365. Furthermore, offloading the burden of authenticating against a domain controller actually makes your applications safer because you don't need to write your own authentication service; therefore, we minimize the chance of vulnerabilities.
How It Works?
This solution uses the LDAP3 python library. It can be installed simplely by doing:pip install ldap3
The ldap3 package in Python is a library for interacting with LDAP (Lightweight Directory Access Protocol) servers. It simplifies tasks like searching, adding, modifying, and deleting entries in LDAP directories. With ldap3, developers can securely connect to LDAP servers, handle authentication, and manage directory data efficiently. It's a popular choice for building authentication systems and enterprise directory management solutions in Python.
My Custom Function I wrote a custom function in Python that utilizes ldap3, with the inputs for username, password, and domain URL or domain controller IP.
from ldap3 import Server, Connection, ALL
def LDAP_AUTH(domain,username,password):
didConnect=False
try:
# Define the server and connection settings
server = Server(f"ldap://{domain}", get_info=ALL)
conn = Connection(server, user=f"{username}@{domain}", password=password, auto_bind=True)
# Attempt to bind (authenticate) the user
conn.bind()
# Check if the bind was successful
if conn.result['result'] == 0:
print("Authentication successful")
didConnect = True
except:
print("Authentication failed")
finally:
# Don't forget to close the connection when you're done
try:
conn.unbind()
except:
''
return didConnect
("conn.result['result'] == 0")
, the function sets didConnect boolean to True. Having the function check our credentials and return a Boolean value True/False makes it very simple to embed into the FastAPI auth service.
Conclusion
Please check out my GitHub repo for the most barebones FastAPI app authenticating against a domain controller. :)