0Pricing
Clojure Functional Programming & JVM Backend Development · Aula

Autenticação e Autorização

Proteja o seu back-end Clojure com autenticação baseada em tokens e autorização baseada em funções usando middleware Ring.

Autenticação e Autorização é uma aula grátis de Clojure Functional Programming & JVM Backend Development no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Clojure Functional Programming & JVM Backend Development, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Clojure Functional Programming & JVM Backend Development inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

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) ; => true

What 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

Perguntas Frequentes

A aula “Autenticação e Autorização” é grátis?

Sim — o texto completo de “Autenticação e Autorização” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Clojure Functional Programming & JVM Backend Development, atualize para CoddyKit PRO. O curso de Clojure Functional Programming & JVM Backend Development inclui 4 aulas no total.

O que vou aprender em “Autenticação e Autorização”?

Proteja o seu back-end Clojure com autenticação baseada em tokens e autorização baseada em funções usando middleware Ring. Você pratica Clojure Functional Programming & JVM Backend Development com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Clojure Functional Programming & JVM Backend Development?

Nenhuma experiência prévia é necessária. Clojure Functional Programming & JVM Backend Development no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.

Quanto tempo leva a aula “Autenticação e Autorização”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Clojure Functional Programming & JVM Backend Development?

Sim. Cada aula de Clojure Functional Programming & JVM Backend Development inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Criação de uma API RESTful
  2. Arquiteturas orientadas a eventos
  3. Design de sistemas e padrões de escalabilidade
  4. Autenticação e Autorização
← Voltar para Clojure Functional Programming & JVM Backend Development