Securing Flask APIs with Tokens

Tutorial 5 of 5

1. Introduction

In this tutorial, we will learn how to secure a Flask API using authentication tokens. Token-based authentication is a key component in API security, which helps in ensuring that each request to your API is authenticated, thus protecting sensitive information from unauthorized access.

By the end of this tutorial, you will know how to:

  • Implement token-based authentication in a Flask API
  • Generate and validate authentication tokens
  • Secure endpoints with tokens

Prerequisites:

  • Basic knowledge of Python programming language
  • Familiarity with Flask web framework
  • Python and Flask installed on your machine

2. Step-by-Step Guide

We will be using Flask-JWT-Extended, a Flask extension that provides JWT support (JSON Web Token). JWT is a compact, URL-safe means of representing claims to be transferred between two parties.

First, install Flask-JWT-Extended using pip:

pip install Flask-JWT-Extended

Token Generation

In your Flask application, you'll need to setup Flask-JWT-Extended:

from flask import Flask
from flask_jwt_extended import JWTManager

app = Flask(__name__)
app.config['JWT_SECRET_KEY'] = 'your-secret-key'  # change this in your production app
jwt = JWTManager(app)

In this example, the 'JWT_SECRET_KEY' is used to sign the tokens. It should be a complex and secure string in a production application.

Token Validation

Let's create an endpoint that requires a valid JWT to access:

from flask_jwt_extended import jwt_required

@app.route('/protected', methods=['GET'])
@jwt_required
def protected():
    return {'message': 'This is a protected endpoint.'}

3. Code Examples

Example 1: Creating a Login Endpoint

Here we'll create a login endpoint that generates and returns a JWT when given correct login credentials.

from flask import request, jsonify
from flask_jwt_extended import create_access_token

@app.route('/login', methods=['POST'])
def login():
    if not request.is_json:
        return jsonify({"msg": "Missing JSON in request"}), 400

    username = request.json.get('username', None)
    password = request.json.get('password', None)

    # Replace with your own username/password checking
    if username != 'test' or password != 'test':
        return jsonify({"msg": "Bad username or password"}), 401

    # Create the token
    access_token = create_access_token(identity=username)
    return jsonify(access_token=access_token), 200

Example 2: Accessing Protected Endpoint

You can access the protected endpoint using the token generated from the login endpoint. The token should be included in the Authorization header as a Bearer token.

import requests

# Replace with your generated token
token = 'your-token'

response = requests.get('http://localhost:5000/protected', headers={'Authorization': f'Bearer {token}'})
print(response.json())

4. Summary

In this tutorial, we've covered how to:

  • Set up Flask-JWT-Extended in your Flask application
  • Create a login endpoint that generates JWTs
  • Secure endpoints with the JWTs

Next steps include exploring more about JWTs, such as refreshing tokens and blacklisting. You might also want to look into more advanced topics, such as role-based access control.

5. Practice Exercises

  1. Create a /logout endpoint that invalidates the current token.
  2. Implement an endpoint that refreshes the token.
  3. Enhance the login endpoint to check a database for user credentials instead of hard-coded ones.

For these exercises, you'll need to understand how to blacklist tokens and how to interact with databases using Flask. You can refer to the Flask-JWT-Extended documentation and Flask-SQLAlchemy tutorials for help.