Skip to main content

Biblioteca de autenticação com o Gov.br para FastAPI, Flask e Django.

Project description

GovBR Auth

Autentique usuários com o Gov.br usando FastAPI, Flask, Django ou sua própria stack personalizada.

💡 Motivação

A criação desta biblioteca nasceu de uma necessidade real: ao tentar integrar com o Login Único Gov.br, enfrentei diversas dificuldades iniciais — desde entender o fluxo de autenticação com PKCE, até decidir qual abordagem seria mais segura: fazer tudo no frontend ou delegar ao backend?

Veja também: 🔒 Boas práticas adotadas


🚀 Instalação

Instalação mínima (somente núcleo de serviços):

pip install govbr-auth

Instalação com framework específico:

pip install govbr-auth[fastapi]
# ou
pip install govbr-auth[flask]
# ou
pip install govbr-auth[django]

Instalação completa (todos os frameworks):

pip install govbr-auth[full]

⚙️ Configuração

Via .env:

GOVBR_REDIRECT_URI=
GOVBR_CLIENT_ID=
GOVBR_CLIENT_SECRET=
GOVBR_CODE_CHALLENGE_METHOD=S256
GOVBR_SCOPE=openid email profile
GOVBR_RESPONSE_TYPE=code
CRIPT_VERIFIER_SECRET=
GOVBR_AUTH_URL=https://sso.staging.acesso.gov.br/authorize
GOVBR_TOKEN_URL=https://sso.staging.acesso.gov.br/token
GOVBR_USER_INFO=https://api.acesso.gov.br/userinfo
JWT_SECRET=chave_super_secreta
JWT_EXPIRES_MINUTES=60
JWT_ALGORITHM=HS256

Ou via código:

from govbr_auth.core.config import GovBrConfig

config = GovBrConfig(
        client_id="...",
        client_secret="...",
        redirect_uri="https://...",
        cript_verifier_secret="...",
)

🔑 Gerando o cript_verifier_secret

Certifique-se de gerar um valor único e seguro para o cript_verifier_secret. Esse valor deve ser mantido em segredo e não deve ser compartilhado publicamente, pois é usado para proteger a troca de tokens entre o cliente e o servidor de autenticação. Você pode usar a função generate_cript_verifier_secret para isso.

from govbr_auth.utils import generate_cript_verifier_secret
print(generate_cript_verifier_secret())
# gera um valor válido para o `cript_verifier_secret`, exemplo: Vvd9H5VC2Aqk-dwFOJX6MvQTuZZARmb37y7un9wkj0c=

🧩 Uso com FastAPI

from fastapi import FastAPI
from govbr_auth.controller import GovBrConnector

app = FastAPI()
connector = GovBrConnector(config,
                           prefix="/auth",
                           authorize_endpoint="/govbr/authorize",
                           authenticate_endpoint="/govbr/callback",
                           )
connector.init_fastapi(app)

🌐 Uso com Flask

from flask import Flask, jsonify, request
from govbr_auth import GovBrConnector, GovBrConfig

def after_auth(data, request):
    user = data["id_token_decoded"]
    return jsonify({
        "mensagem": "Login efetuado com sucesso!",
        "usuario": user["name"],
        "cpf": user["sub"]
    })

config = GovBrConfig.from_env()
connector = GovBrConnector(config,
                           prefix="/auth",
                           authorize_endpoint="/govbr/authorize",
                           authenticate_endpoint="/govbr/callback",
                           on_auth_success=after_auth
                           )

app = Flask(__name__)
connector.init_flask(app)

🛠️ Uso com Django

from django.http import JsonResponse
from govbr_auth import GovBrConnector, GovBrConfig

def after_auth(data, request):
    user = data["id_token_decoded"]
    return JsonResponse({
        "mensagem": "Usuário autenticado!",
        "nome": user.get("name"),
        "cpf": user.get("sub")
    })


config = GovBrConfig.from_env()

connector = GovBrConnector(config,
                           prefix="/auth",
                           authorize_endpoint="/govbr/authorize",
                           authenticate_endpoint="/govbr/callback",
                           on_auth_success=after_auth
                           )

urlpatterns = [
    *connector.init_django(),
]

🧱 Uso com Stack Personalizada (baixo nível)

Você pode usar os serviços principais diretamente, de forma assíncrona ou síncrona:

Async

from govbr_auth.core.govbr import GovBrAuthorize, GovBrIntegration

authorize = GovBrAuthorize(config)
auth_url = authorize.build_authorize_url()

integration = GovBrIntegration(config)
result = await integration.async_exchange_code_for_token(code, state)

Sync

from govbr_auth.core.govbr import GovBrAuthorize, GovBrIntegration

authorize = GovBrAuthorize(config)
auth_url = authorize.build_authorize_url_sync()

integration = GovBrIntegration(config)
result = integration.exchange_code_for_token_sync(code, state)

Ideal para:

  • APIs customizadas
  • Serviços Lambda/FaaS
  • Apps que não usam frameworks web tradicionais

📌 Endpoints Disponíveis (padrão)

  • GET /auth/govbr/authorize → Retorna a URL de autorização Gov.br com PKCE
  • GET /auth/govbr/authenticate → Recebe code e state, troca por tokens e retorna dados decodificados

Os caminhos podem ser personalizados via GovBrConfig

✅ Testes

pytest tests/

📄 Licença

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

govbr_auth-0.1.2.tar.gz (16.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

govbr_auth-0.1.2-py3-none-any.whl (16.3 kB view details)

Uploaded Python 3

File details

Details for the file govbr_auth-0.1.2.tar.gz.

File metadata

  • Download URL: govbr_auth-0.1.2.tar.gz
  • Upload date:
  • Size: 16.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.2

File hashes

Hashes for govbr_auth-0.1.2.tar.gz
Algorithm Hash digest
SHA256 84b129188fda79adbfeb779e5be27ec5b9866b23d8cb5f1408564906904dca26
MD5 4ac295fd08364986ef8fd2d6f1ed4695
BLAKE2b-256 f4d540e7ae4881fcd41ce24bb1a09ad760e493dbe5e2a33d5b41b6879a04bf39

See more details on using hashes here.

File details

Details for the file govbr_auth-0.1.2-py3-none-any.whl.

File metadata

  • Download URL: govbr_auth-0.1.2-py3-none-any.whl
  • Upload date:
  • Size: 16.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.2

File hashes

Hashes for govbr_auth-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 fcbd0a23156b02d2d1bf86e1537438df34db58f86394a3d93a93665b73a495e5
MD5 ca8e7d80bec5d6522782e64835891279
BLAKE2b-256 de34f01b4f8960a938081f0bb6c1f5328a67cd46d14a9f22ac05ef5a9c5975e3

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page