Django Academy · Aula

Autenticação por token e JWT

Autentique clientes da API com segurança

Aula 3 de 413 etapas

Autenticação por token e JWT é uma aula grátis de Django Academy no CoddyKit. Esta é a aula 3 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 Django Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Django Academy inclui 4 aulas no total.

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

APIs Need Stateless Auth

Browsers use sessions, but API clients often have no cookies. Token authentication lets a client prove who it is on every request instead.

How a Token Works

The user logs in once and gets a token string. They send it with each request, and DRF maps it back to the right user.

Enabling TokenAuthentication

Add the authtoken app and turn on TokenAuthentication so DRF knows to read tokens from incoming requests.

INSTALLED_APPS += ['rest_framework.authtoken']

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ],
}

Issuing a Token

DRF gives you a built-in obtain_auth_token view. Post a username and password to it, and it returns that user's token.

from rest_framework.authtoken.views import obtain_auth_token

urlpatterns = [
    path('api-token-auth/', obtain_auth_token),
]

Sending the Token

The client puts the token in the Authorization header, prefixed with the word Token, on every protected call. 🔑

Authorization: Token 9944b09199c62bcf9418ad846dd0e4

The Limit of Simple Tokens

A DRF token never expires and is just a database lookup. For larger systems, a JWT adds expiry and self-contained data.

What a JWT Carries

A JSON Web Token is a signed string holding claims like the user id and an expiry time. The server trusts it without a DB hit.

Adding SimpleJWT

Install djangorestframework-simplejwt and register its authentication class to swap tokens for JWTs.

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ],
}

Access and Refresh Tokens

SimpleJWT gives two tokens: a short-lived access token for requests and a longer refresh token to get a new access token.

JWT Login Endpoints

Wire up TokenObtainPairView to log in and TokenRefreshView to renew, and your JWT flow is ready.

from rest_framework_simplejwt.views import (
    TokenObtainPairView, TokenRefreshView)

urlpatterns = [
    path('token/', TokenObtainPairView.as_view()),
    path('token/refresh/', TokenRefreshView.as_view()),
]

Sending a Bearer Token

JWT clients use the Bearer scheme in the Authorization header instead of the Token word DRF tokens use. 🎟️

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9

Quick Check

One key difference separates DRF tokens from JWTs.

Recap: Proving Identity

You learned to authenticate API clients with DRF tokens for simplicity and JWTs for expiry and scale, both sent in the Authorization header. 🎉

Grátis para começar

Aprenda Python com um tutor de IA — grátis

Escreva e execute código real no seu navegador, obtenha ajuda instantânea de um tutor de IA 24/7 e continue de onde parou na web ou no app.

Cursos
30
Aulas
120

Perguntas Frequentes

A aula “Autenticação por token e JWT” é grátis?

Sim — o texto completo de “Autenticação por token e JWT” é 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 Django Academy, atualize para CoddyKit PRO. O curso de Django Academy inclui 4 aulas no total.

O que vou aprender em “Autenticação por token e JWT”?

Autentique clientes da API com segurança Você pratica Django Academy 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 Django Academy?

Nenhuma experiência prévia é necessária. Django Academy 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 3 de 4.

Quanto tempo leva a aula “Autenticação por token e JWT”?

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 Django Academy?

Sim. Cada aula de Django Academy 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. ModelViewSet e roteadores
  2. Permissões e limitação de requisições
  3. Autenticação por token e JWT
  4. Filtragem, pesquisa e paginação
← Voltar para Django Academy