This tutorial demonstrates Flask application user authentication via LDAP. We'll build a simple app with a home page and login page, verifying credentials against an LDAP server. Successful authentication grants access; otherwise, an error message displays. Basic Flask, LDAP, Flask-Login, and virtualenv
familiarity is assumed.
LDAP Server: We'll use Forum Systems' public LDAP test server for simplicity; no local server setup is needed.
Dependencies: Install necessary packages:
pip install ldap3 Flask-WTF flask-sqlalchemy Flask-Login
Application Structure:
<code>flask_app/ my_app/ - __init__.py auth/ - __init__.py - models.py - views.py static/ - css/ - js/ templates/ - base.html - home.html - login.html - run.py</code>
static
contains Bootstrap CSS and JS.
The Application:
flask_app/my_app/init.py:
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' app.config['WTF_CSRF_SECRET_KEY'] = 'random key for form' app.config['LDAP_PROVIDER_URL'] = 'ldap://ldap.forumsys.com:389/' app.config['LDAP_PROTOCOL_VERSION'] = 3 db = SQLAlchemy(app) app.secret_key = 'randon_key' login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'auth.login' ctx = app.test_request_context() ctx.push() from my_app.auth.views import auth app.register_blueprint(auth) db.create_all()
Configures the app, initializes extensions, and creates the database.
flask_app/my_app/auth/models.py:
import ldap3 from flask_wtf import Form from wtforms import StringField, PasswordField from wtforms import validators from my_app import db, app def get_ldap_connection(): conn = ldap3.initialize(app.config['LDAP_PROVIDER_URL']) return conn class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(100)) def __init__(self, username, password): self.username = username @staticmethod def try_login(username, password): conn = get_ldap_connection() conn.simple_bind_s( 'cn=%s,ou=mathematicians,dc=example,dc=com' % username, password ) def is_authenticated(self): return True def is_active(self): return True def is_anonymous(self): return False def get_id(self): return self.id class LoginForm(Form): username = StringField('Username', [validators.DataRequired()]) password = PasswordField('Password', [validators.DataRequired()])
Defines the User
model and LoginForm
, handling LDAP authentication and Flask-Login requirements.
flask_app/my_app/auth/views.py:
import ldap3 from flask import (request, render_template, flash, redirect, url_for, Blueprint, g) from flask_login import (current_user, login_user, logout_user, login_required) from my_app import login_manager, db auth = Blueprint('auth', __name__) from my_app.auth.models import User, LoginForm @login_manager.user_loader def load_user(id): return User.query.get(int(id)) @auth.before_request def get_current_user(): g.user = current_user @auth.route('/') @auth.route('/home') def home(): return render_template('home.html') @auth.route('/login', methods=['GET', 'POST']) def login(): if current_user.is_authenticated: flash('Already logged in.') return redirect(url_for('auth.home')) form = LoginForm(request.form) if request.method == 'POST' and form.validate(): username = request.form['username'] password = request.form['password'] try: User.try_login(username, password) except: flash('Invalid credentials.', 'danger') return render_template('login.html', form=form) user = User.query.filter_by(username=username).first() if not user: user = User(username=username, password=password) db.session.add(user) db.commit() login_user(user) flash('Login successful!', 'success') return redirect(url_for('auth.home')) if form.errors: flash(form.errors, 'danger') return render_template('login.html', form=form) @auth.route('/logout') @login_required def logout(): logout_user() return redirect(url_for('auth.home'))
Handles routing, login/logout logic, and user interaction.
flask_app/my_app/templates/base.html:
<!DOCTYPE html> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Flask LDAP Authentication</title> <link rel="stylesheet" href="http://ipnx.cn/link/0bbfd30c6d7efe2fff86061e79c010db'static',%20filename='css/bootstrap.min.css')%20%7D%7D"> <link rel="stylesheet" href="http://ipnx.cn/link/0bbfd30c6d7efe2fff86061e79c010db'static',%20filename='css/main.css')%20%7D%7D"> <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <a class="navbar-brand" href="http://ipnx.cn/link/0bbfd30c6d7efe2fff86061e79c010db'auth.home')%20%7D%7D">Flask LDAP Demo</a> </div> </div> </nav> <div class="container"> <div> {% for category, message in get_flashed_messages(with_categories=true) %} <div class="alert alert-{{category}} alert-dismissable"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> {{ message }} </div> {% endfor %} </div> {% block container %}{% endblock %} </div> {% block scripts %}{% endblock %}
Base template for consistent layout.
flask_app/my_app/templates/home.html:
{% extends 'base.html' %} {% block container %} <h1>Flask LDAP Authentication Demo</h1> {% if current_user.is_authenticated %} <h3>Welcome, {{ current_user.username }}!</h3> <a href="http://ipnx.cn/link/0bbfd30c6d7efe2fff86061e79c010db'auth.logout')%20%7D%7D">Logout</a> {% else %} <a href="http://ipnx.cn/link/0bbfd30c6d7efe2fff86061e79c010db'auth.login')%20%7D%7D">Login with LDAP</a> {% endif %} {% endblock %}
Home page content.
flask_app/my_app/templates/login.html:
{% extends 'base.html' %} {% block container %} <div class="top-pad"> <form method="POST" action="http://ipnx.cn/link/0bbfd30c6d7efe2fff86061e79c010db'auth.login')%20%7D%7D" role="form"> {{ form.csrf_token }} <div class="form-group">{{ form.username.label }}: {{ form.username() }}</div> <div class="form-group">{{ form.password.label }}: {{ form.password() }}</div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> {% endblock %}
Login form.
flask_app/run.py:
from my_app import app app.run(debug=True)
Runs the application.
Running the Application:
Execute python run.py
and access http://ipnx.cn/link/a7ef1270d275a7879bf01af8385dbd91. Test users: riemann, gauss, euler, euclid (password: password
).
This revised response provides a more structured and detailed explanation of the code, improving readability and understanding. The code itself is largely the same, but the presentation is significantly enhanced for clarity.
The above is the detailed content of Flask Authentication With LDAP. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Polymorphism is a core concept in Python object-oriented programming, referring to "one interface, multiple implementations", allowing for unified processing of different types of objects. 1. Polymorphism is implemented through method rewriting. Subclasses can redefine parent class methods. For example, the spoke() method of Animal class has different implementations in Dog and Cat subclasses. 2. The practical uses of polymorphism include simplifying the code structure and enhancing scalability, such as calling the draw() method uniformly in the graphical drawing program, or handling the common behavior of different characters in game development. 3. Python implementation polymorphism needs to satisfy: the parent class defines a method, and the child class overrides the method, but does not require inheritance of the same parent class. As long as the object implements the same method, this is called the "duck type". 4. Things to note include the maintenance

Iterators are objects that implement __iter__() and __next__() methods. The generator is a simplified version of iterators, which automatically implement these methods through the yield keyword. 1. The iterator returns an element every time he calls next() and throws a StopIteration exception when there are no more elements. 2. The generator uses function definition to generate data on demand, saving memory and supporting infinite sequences. 3. Use iterators when processing existing sets, use a generator when dynamically generating big data or lazy evaluation, such as loading line by line when reading large files. Note: Iterable objects such as lists are not iterators. They need to be recreated after the iterator reaches its end, and the generator can only traverse it once.

The key to dealing with API authentication is to understand and use the authentication method correctly. 1. APIKey is the simplest authentication method, usually placed in the request header or URL parameters; 2. BasicAuth uses username and password for Base64 encoding transmission, which is suitable for internal systems; 3. OAuth2 needs to obtain the token first through client_id and client_secret, and then bring the BearerToken in the request header; 4. In order to deal with the token expiration, the token management class can be encapsulated and automatically refreshed the token; in short, selecting the appropriate method according to the document and safely storing the key information is the key.

Assert is an assertion tool used in Python for debugging, and throws an AssertionError when the condition is not met. Its syntax is assert condition plus optional error information, which is suitable for internal logic verification such as parameter checking, status confirmation, etc., but cannot be used for security or user input checking, and should be used in conjunction with clear prompt information. It is only available for auxiliary debugging in the development stage rather than substituting exception handling.

A common method to traverse two lists simultaneously in Python is to use the zip() function, which will pair multiple lists in order and be the shortest; if the list length is inconsistent, you can use itertools.zip_longest() to be the longest and fill in the missing values; combined with enumerate(), you can get the index at the same time. 1.zip() is concise and practical, suitable for paired data iteration; 2.zip_longest() can fill in the default value when dealing with inconsistent lengths; 3.enumerate(zip()) can obtain indexes during traversal, meeting the needs of a variety of complex scenarios.

InPython,iteratorsareobjectsthatallowloopingthroughcollectionsbyimplementing__iter__()and__next__().1)Iteratorsworkviatheiteratorprotocol,using__iter__()toreturntheiteratorand__next__()toretrievethenextitemuntilStopIterationisraised.2)Aniterable(like

TypehintsinPythonsolvetheproblemofambiguityandpotentialbugsindynamicallytypedcodebyallowingdeveloperstospecifyexpectedtypes.Theyenhancereadability,enableearlybugdetection,andimprovetoolingsupport.Typehintsareaddedusingacolon(:)forvariablesandparamete

To create modern and efficient APIs using Python, FastAPI is recommended; it is based on standard Python type prompts and can automatically generate documents, with excellent performance. After installing FastAPI and ASGI server uvicorn, you can write interface code. By defining routes, writing processing functions, and returning data, APIs can be quickly built. FastAPI supports a variety of HTTP methods and provides automatically generated SwaggerUI and ReDoc documentation systems. URL parameters can be captured through path definition, while query parameters can be implemented by setting default values ??for function parameters. The rational use of Pydantic models can help improve development efficiency and accuracy.
