0Pricing
Flask Academy · Lezione

Proteggere gli endpoint con jwt_required

Verifichi il token a ogni chiamata API.

Proteggere gli endpoint con jwt_required è una lezione Flask Academy gratuita su CoddyKit. Questa è la lezione 3 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Flask Academy, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Flask Academy include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

Guarding a Route

A token is only useful if some routes demand it. The jwt_required decorator turns any view into a members-only endpoint. 🔒

Apply the Decorator

Stack @jwt_required() under your route. Now the view only runs when a valid, unexpired token arrives.

@app.get("/profile")
@jwt_required()
def profile():
    ...

Where the Token Goes

Clients send the token in the Authorization header using the Bearer scheme. Flask-JWT-Extended reads it from there automatically.

Authorization: Bearer <your-token>

Automatic Rejection

No token, or a bad one? The decorator stops the request before your code runs and returns a 401. You write zero checking logic.

Who Is Calling

Inside a guarded view, call get_jwt_identity to read the identity you signed at login, usually the user id.

from flask_jwt_extended import get_jwt_identity
uid = get_jwt_identity()

Read the Full Claims

Need extra claims like a role? get_jwt returns the whole payload as a dict so you can branch on what is inside.

from flask_jwt_extended import get_jwt
role = get_jwt().get("role")

Use the Identity

With the user id in hand, load that user and serve their data. The token told you who, so the rest is normal Flask. 🙂

user = User.query.get(get_jwt_identity())

Optional Protection

Want a page that adapts whether or not someone is logged in? Use optional=True so the view runs either way.

@jwt_required(optional=True)

Customize the Error

Register an unauthorized_loader to return a friendly JSON message instead of the default when a token is missing.

@jwt.unauthorized_loader
def missing(reason):
    return {"msg": reason}, 401

Expired Tokens

An expired token is also rejected by the decorator. The client must log in again or refresh to keep going, which keeps stolen tokens short-lived.

Never Trust the Body

Read the caller from the token, never from a user id in the request body. The signature is what makes the identity trustworthy.

Quick Check

Recall how a guarded view learns who is calling.

Recap

Add @jwt_required() to guard a route, send the token as a Bearer header, and read the caller with get_jwt_identity. 🔐

Domande Frequenti

La lezione «Proteggere gli endpoint con jwt_required» è gratuita?

Sì — il testo completo di «Proteggere gli endpoint con jwt_required» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Flask Academy, passa a CoddyKit PRO. Il corso Flask Academy include 4 lezioni in totale.

Cosa imparerò in «Proteggere gli endpoint con jwt_required»?

Verifichi il token a ogni chiamata API. Eserciti Flask Academy con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Flask Academy?

Non è richiesta alcuna esperienza precedente. Flask Academy su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 3 di 4.

Quanto tempo richiede la lezione «Proteggere gli endpoint con jwt_required»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Flask Academy?

Sì. Ogni lezione Flask Academy include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Sessioni e token stateless
  2. Emettere access token al login
  3. Proteggere gli endpoint con jwt_required
  4. Refresh token e scadenza
← Torna a Flask Academy