Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use JWTs as one part of a security design, not as the entire design. A secure Flask API authenticates credentials, signs short-lived access tokens with a private key, verifies those tokens over HTTPS, and performs authorization checks for every protected resource. The example below uses Flask-JWT-Extended 4.7.4-style APIs, including JWTManager, create_access_token, @jwt_required(), and get_jwt_identity().

What a secure JWT flow must do

A client submits credentials to a login endpoint. The server verifies the account and password hash, then returns an access token whose subject identifies the user. On later requests, the client sends that token in an Authorization: Bearer header. Flask verifies the signature and registered claims before your view runs. The view then checks whether that user is allowed to perform the requested operation on the requested record.

These are separate decisions:

  • Authentication: does this token represent a valid, unexpired principal?
  • Authorization: may that principal read or modify this particular resource?
  • Transport security: was the credential protected in transit?

OWASP states that secure REST services must provide HTTPS endpoints and that non-public REST services must perform access control at each API endpoint.

Install and configure Flask-JWT-Extended

Install the dependencies

python -m venv .venv
. .venv/bin/activate       # Windows: .venvScriptsactivate
pip install Flask Flask-JWT-Extended Werkzeug

Keep the signing key outside source control

The signing key lets an attacker mint tokens your API will accept. Generate a long random value, store it in your secret manager or deployment environment, and never commit it. Changing the key invalidates outstanding tokens, so plan key rotation as an operational event.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
export JWT_SECRET_KEY="replace-with-a-long-random-production-secret"

Initialize the extension before serving requests

import os
from flask import Flask
from flask_jwt_extended import JWTManager

def create_app():
    app = Flask(__name__)
    secret = os.environ.get("JWT_SECRET_KEY")
    if not secret:
        raise RuntimeError("JWT_SECRET_KEY is not configured")

    app.config.update(
        JWT_SECRET_KEY=secret,
        JWT_ALGORITHM="HS256",
        JWT_ACCESS_TOKEN_EXPIRES=900,  # 15 minutes; choose for your risk profile
    )
    JWTManager(app)
    return app

Use an asymmetric signing design and a key-management process instead when multiple services must verify tokens without receiving a shared signing secret. Whichever algorithm you choose, configure it explicitly and reject unsecured tokens; never allow an untrusted token header to choose the verification algorithm.

Authenticate users before issuing a token

The login route must look up the account and verify the submitted password with your password-hashing implementation. The hard-coded username/password shown in many introductory examples is only a demonstration and is not an authentication system.

from flask import request, jsonify
from flask_jwt_extended import create_access_token
from werkzeug.security import check_password_hash

# Replace this with a database query.
USERS = {
    "u_123": {
        "email": "sam@example.com",
        "password_hash": "pbkdf2:sha256:600000$example$replace-me"
    }
}

def find_user_by_email(email):
    return next((u for u in USERS.values() if u["email"] == email), None)

@app.post("/login")
def login():
    data = request.get_json(silent=True) or {}
    email = data.get("email", "")
    password = data.get("password", "")
    user = find_user_by_email(email)

    if not user or not check_password_hash(user["password_hash"], password):
        return jsonify(error="invalid credentials"), 401

    token = create_access_token(identity="u_123")
    return jsonify(access_token=token), 200

Use a stable internal user identifier as the identity rather than an email address that may change. Return the same failure message for an unknown account and a wrong password, and rate-limit or otherwise protect repeated login attempts.

Protect routes and retrieve the identity

from flask_jwt_extended import jwt_required, get_jwt_identity

@app.get("/me")
@jwt_required()
def me():
    user_id = get_jwt_identity()
    return jsonify(user_id=user_id)

@jwt_required() performs the default access-token checks before the view executes. Keep public endpoints un-decorated intentionally. The extension also supports requirements such as fresh tokens and refresh tokens; retain the default token-type verification unless you have a reviewed reason to change it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Authorization is a second, resource-specific check

A valid token does not imply permission to access every object. Fetch the requested record and compare its owner, tenant, role, or policy before returning or changing it.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
@app.delete("/projects/<project_id>")
@jwt_required()
def delete_project(project_id):
    user_id = get_jwt_identity()
    project = load_project(project_id)
    if project is None:
        return jsonify(error="not found"), 404
    if project.owner_id != user_id and not user_is_admin(user_id):
        return jsonify(error="forbidden"), 403
    delete_from_database(project_id)
    return "", 204

Apply this decision at every non-public endpoint, including nested resources, exports, administrative actions, and background-job status endpoints. Do not rely on a client-supplied user_id when the verified token identity is available.

Validate claims and token integrity

JWT payloads are readable by anyone holding the token; readability is not trust. Trust claims only after signature verification and validation under your configured rules. Check the expiration (exp) and not-before (nbf) times, and configure an expected issuer and audience when your architecture uses them.

app.config.update(
    JWT_DECODE_ISSUER="https://api.example.com",
    JWT_DECODE_AUDIENCE="example-api",
)

Use a single, explicitly configured algorithm. Do not accept an algorithm named by the incoming header, and do not accept an unsecured token. Allow only small, deliberate identity and authorization claims; avoid putting secrets or sensitive personal data in the payload.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose a safe token transport

Transport Best fit Required precautions
Authorization header Native apps, service clients, and APIs that attach credentials explicitly; this is the extension’s default. Use HTTPS, protect client storage, and never place the token in a URL.
Secure cookie Browser applications that benefit from automatic cookie handling. Use HTTPS-only cookie settings and keep CSRF protection enabled for state-changing requests. Flask-JWT-Extended documents a double-submit CSRF pattern.
Query string Avoid for ordinary access tokens. URLs can be retained in browser history, proxies, analytics systems, and server logs.

There is no universal client-storage answer: browser, mobile, service-to-service, and mixed architectures have different threat models. Decide based on the client and deployment, then document the choice.

Send the bearer token correctly

curl https://api.example.com/me 
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

Use HTTPS from the client to the edge and from the edge to the Flask service. Do not log the Authorization header, full tokens, passwords, or signing keys. Strip sensitive headers from reverse-proxy access logs and error reports.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Expiration, refresh, logout, and revocation

Keep access tokens bounded

Set an expiration appropriate to the application’s risk and use a separate refresh flow if users need longer sessions. A shorter access-token lifetime limits the window after theft but increases refresh traffic.

Understand logout

A JWT remains cryptographically valid until it expires. Deleting it from a client does not recall a copy an attacker already obtained. If logout, password reset, account disablement, or incident response must invalidate it early, check a server-side denylist.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Denylist the token ID

from flask_jwt_extended import get_jwt

REVOKED_JTIS = set()  # Use durable shared storage in production.

@app.post("/logout")
@jwt_required()
def logout():
    claims = get_jwt()
    REVOKED_JTIS.add(claims["jti"])
    return jsonify(message="token revoked"), 200

@jwt.token_in_blocklist_loader
def is_revoked(jwt_header, jwt_payload):
    return jwt_payload["jti"] in REVOKED_JTIS

An in-memory set disappears on restart and is not shared by multiple workers. Use a database or shared cache with a TTL no longer than the token’s remaining lifetime, and fail safely if the revocation store is unavailable.

Return useful, non-leaking errors

  • 401 Unauthorized: no token, malformed token, invalid signature, expired token, wrong token type, or revoked token.
  • 403 Forbidden: the token is valid but the principal is not permitted to perform this operation.
  • 404 Not Found: the resource does not exist; in some applications, deliberately use a non-disclosing response to avoid revealing its existence.

Use the extension’s error callbacks to return a consistent JSON shape, while keeping cryptographic details and token contents out of responses.

Operational checklist

  • Serve every credential-bearing endpoint over HTTPS.
  • Load a long, random secret from a secret manager or environment and exclude it from source control.
  • Verify passwords with a password-hashing library, not string comparison.
  • Use a stable subject identifier and validate issuer, audience, expiration, and not-before claims where applicable.
  • Perform authorization against the requested resource on every protected endpoint.
  • Use the Authorization header or a CSRF-protected secure cookie; avoid query parameters.
  • Set access-token expiry and design refresh behavior before deployment.
  • Implement a durable JTI denylist when early revocation is required.
  • Redact tokens, secrets, and credentials from logs and monitoring.
  • Test expired, malformed, wrong-audience, wrong-issuer, revoked, and insufficient-permission requests.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Common failures and fixes

Every protected request returns 401

Check that the header is exactly Authorization: Bearer <token>, that the token has not expired, and that the service is using the same key and algorithm that issued it. Verify that a proxy is not stripping the header.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

A token works after logout

That is expected unless a blocklist check runs on every protected request. Add a JTI denylist backed by shared storage and retain entries until expiration.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A user can read another user’s record

The route authenticates but does not authorize. Compare the verified identity with the record owner, tenant, or policy before returning data.

Cookie authentication fails on POST

Check HTTPS-only cookie settings and send the CSRF value required by the extension’s double-submit protection. Do not disable CSRF merely to make a test pass.

Tokens leak into logs

Remove query-string authentication, redact authorization headers in the proxy and application logger, and review exception-monitoring payload capture.

Key rotation breaks all sessions

Changing the signing key invalidates outstanding tokens. Treat rotation as a planned event, or design a controlled multi-key verification period if your deployment requires it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Or skip the browser setup

If you need screenshots of API documentation, dashboards, or test results while building the service, ScreenshotNeo provides a single-call capture instead of maintaining a headless-browser setup. It removes cookie banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, with the result identified by response headers. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.

See the ScreenshotNeo API documentation for all options. This request saves the returned WebP file:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

The free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 screenshots, and every feature is included on every plan. Create a free ScreenshotNeo account.

Frequently Asked Questions

Should a JWT contain a user’s roles?

It may contain deliberately chosen authorization claims, but the API must still apply current resource-level policy. Do not treat readable payload data as trusted until signature and claim validation succeed.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Can I use one JWT for access and refresh operations?

Use distinct token types and a reviewed refresh design. Keep access tokens short-lived and ensure endpoints enforce the expected token type.

Where should a browser store a bearer token?

There is no universal answer. A secure, CSRF-protected cookie can fit browser flows; other clients may attach a header. Choose according to the client’s threat model and avoid URLs.

What happens if the revocation database is down?

Define this failure mode explicitly. For high-risk operations, fail closed rather than accepting a token whose revocation status cannot be checked.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.