How to implement user authentication in a Flask application

How to Implement User Authentication in a Flask Application

Flask is a micro web framework for Python that offers simplicity and flexibility, making it a popular choice for web developers. One of the key features of any web application is user authentication. In this article, we’ll explore how to implement user authentication in a Flask application, ensuring your users’ data is secure while providing a seamless experience. We’ll cover essential concepts, use cases, and provide actionable coding insights to help you create a robust authentication system.

What is User Authentication?

User authentication is the process of verifying the identity of a user trying to access a web application. It ensures that users are who they claim to be, typically through usernames and passwords. Proper authentication is crucial for protecting sensitive information and resources in any application.

Use Cases for User Authentication

  • Web Applications: For applications that require user-specific data, such as social media platforms or content management systems.
  • APIs: When building APIs, authentication ensures that only authorized users can access certain endpoints.
  • E-commerce Sites: To secure customer information and payment details.
  • Enterprise Applications: For internal software that requires access control.

Setting Up Your Flask Application

Before we dive into authentication, let’s set up a basic Flask application. If you haven’t installed Flask yet, you can do so using pip:

pip install Flask

Project Structure

Create a new directory for your project and set up the following structure:

flask_auth/
│
├── app.py
├── templates/
│   ├── login.html
│   └── home.html
└── static/

Step 1: Basic Flask Application

In app.py, set up a basic Flask application:

from flask import Flask, render_template, redirect, url_for, request, session
from werkzeug.security import generate_password_hash, check_password_hash

app = Flask(__name__)
app.secret_key = 'your_secret_key'  # Change this to a random secret key

Step 2: User Registration

To implement authentication, we first need to create a registration route. This route will allow users to create accounts.

Registration Code

Add the following code in app.py:

users = {}

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        # Hash the password before storing it
        hashed_password = generate_password_hash(password)
        users[username] = hashed_password
        return redirect(url_for('login'))
    return render_template('register.html')

Registration Template

Create a register.html file in the templates directory with the following content:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Register</title>
</head>
<body>
    <h2>Register</h2>
    <form method="POST">
        <input type="text" name="username" placeholder="Username" required>
        <input type="password" name="password" placeholder="Password" required>
        <button type="submit">Register</button>
    </form>
    <a href="{{ url_for('login') }}">Already have an account? Login</a>
</body>
</html>

Step 3: User Login

Next, we’ll set up a login route to authenticate users.

Login Code

Add the following code to app.py:

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        # Check if user exists and password is correct
        if username in users and check_password_hash(users[username], password):
            session['username'] = username
            return redirect(url_for('home'))
        return 'Invalid username or password!'
    return render_template('login.html')

Login Template

Create a login.html file in the templates directory:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
    <h2>Login</h2>
    <form method="POST">
        <input type="text" name="username" placeholder="Username" required>
        <input type="password" name="password" placeholder="Password" required>
        <button type="submit">Login</button>
    </form>
    <a href="{{ url_for('register') }}">Don't have an account? Register</a>
</body>
</html>

Step 4: Home Route

Now, let’s create a home route that users will see after logging in.

Home Code

Add this code to app.py:

@app.route('/home')
def home():
    if 'username' in session:
        return f'Hello, {session["username"]}! <a href="/logout">Logout</a>'
    return redirect(url_for('login'))

Step 5: User Logout

Finally, we need to implement a logout functionality.

Logout Code

Add the following logout route to app.py:

@app.route('/logout')
def logout():
    session.pop('username', None)
    return redirect(url_for('login'))

Testing Your Application

Now that your authentication system is set up, run your Flask application:

python app.py

Visit http://127.0.0.1:5000/register to create a new account. After registering, you can log in and access the home page.

Troubleshooting Common Issues

  • Session Not Working: Ensure you have set a secret key for the Flask application.
  • Password Hashing Issues: Always hash passwords before storing them to enhance security.
  • Flask Debugging: Enable debug mode by setting app.run(debug=True) to get detailed error messages.

Conclusion

Implementing user authentication in a Flask application is straightforward with the right tools and techniques. By following the steps outlined in this article, you can create a secure and user-friendly authentication system. Always remember to prioritize security, particularly when handling user data. Happy coding!

SR
Syed
Rizwan

About the Author

Syed Rizwan is a Machine Learning Engineer with 5 years of experience in AI, IoT, and Industrial Automation.