search
HomeBackend DevelopmentPython TutorialFlask Authentication With LDAP

Flask Authentication With LDAP

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:



    <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="https://www.php.cn/link/0bbfd30c6d7efe2fff86061e79c010db'static',%20filename='css/bootstrap.min.css')%20%7D%7D">
    <link rel="stylesheet" href="https://www.php.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="https://www.php.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 id="Flask-LDAP-Authentication-Demo">Flask LDAP Authentication Demo</h1>
  {% if current_user.is_authenticated %}
    <h3 id="Welcome-current-user-username">Welcome, {{ current_user.username }}!</h3>
    <a href="https://www.php.cn/link/0bbfd30c6d7efe2fff86061e79c010db'auth.logout')%20%7D%7D">Logout</a>
  {% else %}
    <a href="https://www.php.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="https://www.php.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 https://www.php.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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python's Hybrid Approach: Compilation and Interpretation CombinedPython's Hybrid Approach: Compilation and Interpretation CombinedMay 08, 2025 am 12:16 AM

Pythonusesahybridapproach,combiningcompilationtobytecodeandinterpretation.1)Codeiscompiledtoplatform-independentbytecode.2)BytecodeisinterpretedbythePythonVirtualMachine,enhancingefficiencyandportability.

Learn the Differences Between Python's 'for' and 'while' LoopsLearn the Differences Between Python's 'for' and 'while' LoopsMay 08, 2025 am 12:11 AM

ThekeydifferencesbetweenPython's"for"and"while"loopsare:1)"For"loopsareidealforiteratingoversequencesorknowniterations,while2)"while"loopsarebetterforcontinuinguntilaconditionismetwithoutpredefinediterations.Un

Python concatenate lists with duplicatesPython concatenate lists with duplicatesMay 08, 2025 am 12:09 AM

In Python, you can connect lists and manage duplicate elements through a variety of methods: 1) Use operators or extend() to retain all duplicate elements; 2) Convert to sets and then return to lists to remove all duplicate elements, but the original order will be lost; 3) Use loops or list comprehensions to combine sets to remove duplicate elements and maintain the original order.

Python List Concatenation Performance: Speed ComparisonPython List Concatenation Performance: Speed ComparisonMay 08, 2025 am 12:09 AM

ThefastestmethodforlistconcatenationinPythondependsonlistsize:1)Forsmalllists,the operatorisefficient.2)Forlargerlists,list.extend()orlistcomprehensionisfaster,withextend()beingmorememory-efficientbymodifyinglistsin-place.

How do you insert elements into a Python list?How do you insert elements into a Python list?May 08, 2025 am 12:07 AM

ToinsertelementsintoaPythonlist,useappend()toaddtotheend,insert()foraspecificposition,andextend()formultipleelements.1)Useappend()foraddingsingleitemstotheend.2)Useinsert()toaddataspecificindex,thoughit'sslowerforlargelists.3)Useextend()toaddmultiple

Are Python lists dynamic arrays or linked lists under the hood?Are Python lists dynamic arrays or linked lists under the hood?May 07, 2025 am 12:16 AM

Pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)Theyarestoredincontiguousmemoryblocks,whichmayrequirereallocationwhenappendingitems,impactingperformance.2)Linkedlistswouldofferefficientinsertions/deletionsbutslowerindexedaccess,leadingPytho

How do you remove elements from a Python list?How do you remove elements from a Python list?May 07, 2025 am 12:15 AM

Pythonoffersfourmainmethodstoremoveelementsfromalist:1)remove(value)removesthefirstoccurrenceofavalue,2)pop(index)removesandreturnsanelementataspecifiedindex,3)delstatementremoveselementsbyindexorslice,and4)clear()removesallitemsfromthelist.Eachmetho

What should you check if you get a 'Permission denied' error when trying to run a script?What should you check if you get a 'Permission denied' error when trying to run a script?May 07, 2025 am 12:12 AM

Toresolvea"Permissiondenied"errorwhenrunningascript,followthesesteps:1)Checkandadjustthescript'spermissionsusingchmod xmyscript.shtomakeitexecutable.2)Ensurethescriptislocatedinadirectorywhereyouhavewritepermissions,suchasyourhomedirectory.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment