Skip to content

Basic User Authentication in Python Web Apps

5 min read

1. Introduction to User Authentication

User authentication is a crucial component of web applications, allowing users to securely log in and access personalized content. In Python web development, Flask and Django are two popular web frameworks that can help us implement user authentication. In this tutorial, we will focus on Flask, as it is lightweight and beginner-friendly.

Authentication generally involves verifying the identity of users, typically through a combination of a username and a password. We’ll explore the basic steps of building a secure user authentication system.


2. Setting Up the Environment

Before we start, let’s make sure you have everything you need. Follow these steps to set up your development environment.

Prerequisites:

  • Python (preferably version 3.7 or higher)
  • Virtual environment (recommended)
  • Basic knowledge of Python and HTML

Step 1: Install Flask

First, create a new project directory and navigate to it. Then, create a virtual environment and install Flask.

mkdir flask_auth_app
cd flask_auth_app
python3 -m venv venv
source venv/bin/activate  # For Windows, use 'venv\Scripts\activate'
pip install flask

3. Creating a Simple Python Web App with Flask

Let’s create a basic Flask app to begin with. In your project directory, create a file named app.py and add the following code:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return "Welcome to the Flask Authentication App!"

if __name__ == '__main__':
    app.run(debug=True)

Run the app using the command:

python app.py

You should see the Flask development server running on http://127.0.0.1:5000/.


4. Setting Up User Authentication with Flask

In this section, we will add basic user authentication functionality using Flask. We will need a few libraries:

  1. Flask: for the web framework.
  2. Flask-Login: to handle user sessions and login states.
  3. Flask-WTF: for easier form handling (optional).
  4. Werkzeug: for password hashing.

First, install these dependencies:

pip install flask-login flask-wtf werkzeug

Then, update your app.py to include user authentication:

from flask import Flask, render_template, redirect, url_for, request
from flask_login import UserMixin, LoginManager, login_user, login_required, logout_user, current_user
from werkzeug.security import generate_password_hash, check_password_hash

app = Flask(__name__)
app.secret_key = 'your_secret_key'

# Set up Flask-Login
login_manager = LoginManager()
login_manager.init_app(app)

# In-memory user store (use a database in production)
users = {}

class User(UserMixin):
    def __init__(self, id, username, password):
        self.id = id
        self.username = username
        self.password = password

@login_manager.user_loader
def load_user(user_id):
    return users.get(user_id)

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        user = users.get(username)
        if user and check_password_hash(user.password, password):
            login_user(user)
            return redirect(url_for('dashboard'))

    return render_template('login.html')

@app.route('/dashboard')
@login_required
def dashboard():
    return f'Hello, {current_user.username}! Welcome to your dashboard.'

@app.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('login'))

if __name__ == '__main__':
    app.run(debug=True)

5. Handling User Registration

Next, let’s handle user registration. We will create a simple registration form where users can input their username and password.

Create a register.html file in a templates directory:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Register</title>
</head>
<body>
    <h1>Register</h1>
    <form method="POST">
        <label for="username">Username:</label>
        <input type="text" id="username" name="username" required><br><br>
        <label for="password">Password:</label>
        <input type="password" id="password" name="password" required><br><br>
        <button type="submit">Register</button>
    </form>
</body>
</html>

Update the app.py file to handle registration:

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        hashed_password = generate_password_hash(password)

        user = User(username, username, hashed_password)
        users[username] = user
        return redirect(url_for('login'))

    return render_template('register.html')

6. User Login and Session Management

Once registration is complete, users can log in with their credentials. This has already been set up in the login() function we defined earlier. The Flask-Login extension will handle user sessions for us.

To ensure users are logged in before accessing protected content (like the dashboard), we use the @login_required decorator. This is demonstrated in the /dashboard route.


7. Logout and Session Destruction

We can provide a logout feature by simply calling logout_user() in the appropriate route, as seen in the /logout route above. This will destroy the user session and redirect them back to the login page.


8. Best Practices in User Authentication

Here are some important tips to follow when implementing user authentication in your web apps:

  1. Hash Passwords: Never store plain text passwords. Always hash passwords before storing them (using libraries like werkzeug.security).
  2. Use Sessions: Handle user sessions securely using Flask-Login or a similar library.
  3. Use HTTPS: Always use HTTPS (SSL/TLS) to encrypt communication between your app and the user’s browser.
  4. Implement Strong Password Policies: Ensure users create strong passwords by enforcing certain complexity requirements (e.g., length, special characters).
  5. Prevent Brute Force Attacks: Implement rate limiting and account lockout after several failed login attempts.
  6. Store Session Cookies Securely: Ensure your session cookies are secure and have the HttpOnly and Secure flags set.

9. Conclusion

In this tutorial, we covered the basics of implementing user authentication in a Python web app using Flask. We went through:

  • Setting up Flask with Flask-Login
  • Creating user registration and login features
  • Managing user sessions
  • Best practices to ensure secure user authentication

Leave a Reply

Your email address will not be published. Required fields are marked *

×