Autenticazione e autorizzazione
Protegga il backend Clojure con autenticazione basata su token e autorizzazione basata sui ruoli usando il middleware Ring.
Autenticazione e autorizzazione è una lezione Clojure Functional Programming & JVM Backend Development gratuita su CoddyKit. Questa è la lezione 4 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 Clojure Functional Programming & JVM Backend Development, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Clojure Functional Programming & JVM Backend Development include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
AuthN vs AuthZ
Two distinct concerns:
- Authentication (AuthN): who are you?
- Authorization (AuthZ): what are you allowed to do?
You must verify identity before checking permissions.
Hashing Passwords
Never store plain passwords. Use a slow, salted hash like bcrypt via the buddy library.
(require '[buddy.hashers :as hashers])
(def stored (hashers/derive "secret123"))
(hashers/check "secret123" stored) ; => trueWhat Is a JWT?
A JSON Web Token is a signed, self-contained token holding claims (user id, roles, expiry). The server can verify it without a database lookup.
Issuing a Token
On successful login, sign a token containing the user's claims with a secret key.
(require '[buddy.sign.jwt :as jwt])
(defn make-token [user]
(jwt/sign {:user-id (:id user) :role (:role user)}
secret-key))Verifying a Token
On each request, read the token from the Authorization header and verify the signature. An invalid or expired token throws.
(defn verify [token]
(jwt/unsign token secret-key))Authentication Middleware
Wrap handlers so the verified identity is attached to the request, or a 401 is returned.
(defn wrap-auth [handler]
(fn [request]
(if-let [token (bearer-token request)]
(handler (assoc request :identity (verify token)))
{:status 401 :body "Unauthorized"})))Role-Based Authorization
Once identity is known, check roles before allowing an action.
(defn require-role [role handler]
(fn [request]
(if (= role (get-in request [:identity :role]))
(handler request)
{:status 403 :body "Forbidden"})))401 vs 403
Use the right status:
- 401 Unauthorized: not authenticated (no/invalid token)
- 403 Forbidden: authenticated but lacks permission
Protecting Routes
Combine middleware with Compojure to guard specific endpoints while leaving public ones open.
(defroutes app
(GET "/health" [] ok)
(-> (GET "/admin" [] admin-page)
(#(require-role :admin %))
wrap-auth))Token Expiry & Refresh
Set short expiry on access tokens to limit damage if leaked, and issue long-lived refresh tokens to get new ones without re-login.
(jwt/sign {:user-id 1 :exp (+ (now) 900)} secret-key)Security Best Practices
Key rules:
- Always serve auth over HTTPS
- Store secrets in environment variables, not code
- Hash passwords with bcrypt/argon2
- Keep access tokens short-lived
Quick Check
Test your security knowledge.
Recap
You learned to secure a Clojure backend.
- Hash passwords with bcrypt
- Issue and verify JWTs for stateless auth
- Use middleware for AuthN and role checks for AuthZ
- Return 401 vs 403 correctly
Domande Frequenti
La lezione «Autenticazione e autorizzazione» è gratuita?
Sì — il testo completo di «Autenticazione e autorizzazione» è 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 Clojure Functional Programming & JVM Backend Development, passa a CoddyKit PRO. Il corso Clojure Functional Programming & JVM Backend Development include 4 lezioni in totale.
Cosa imparerò in «Autenticazione e autorizzazione»?
Protegga il backend Clojure con autenticazione basata su token e autorizzazione basata sui ruoli usando il middleware Ring. Eserciti Clojure Functional Programming & JVM Backend Development 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 Clojure Functional Programming & JVM Backend Development?
Non è richiesta alcuna esperienza precedente. Clojure Functional Programming & JVM Backend Development su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.
Quanto tempo richiede la lezione «Autenticazione e autorizzazione»?
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 Clojure Functional Programming & JVM Backend Development?
Sì. Ogni lezione Clojure Functional Programming & JVM Backend Development 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
- Creazione di un’API RESTful
- Architetture basate sugli eventi
- Progettazione dei sistemi e pattern di scalabilità
- Autenticazione e autorizzazione