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
def after_auth(data, request):
    user = data["id_token_decoded"]
    return {
        "mensagem": "Login efetuado com sucesso!",
        "usuario": user["name"],
        "cpf": user["sub"]
    }
app = FastAPI()
connector = GovBrConnector(config,
                           prefix="/auth",
                           authorize_endpoint="/govbr/authorize",
                           authenticate_endpoint="/govbr/callback",
                           on_auth_success=after_auth
                           )
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.4.tar.gz (17.6 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.4-py3-none-any.whl (16.8 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for govbr_auth-0.1.4.tar.gz
Algorithm Hash digest
SHA256 61c7265e1ae779f08a15b297bfd0ce2c4279d0dd3c75247c432a567dfe22ca80
MD5 05efb5f9e1d90e9161caf9bf025504c9
BLAKE2b-256 07d1ba35cbdd0ac07b3a28ce4f2bdc4a04ba85f049d2143396ef1cf5f0c10d87

See more details on using hashes here.

File details

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

File metadata

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

File hashes

Hashes for govbr_auth-0.1.4-py3-none-any.whl
Algorithm Hash digest
SHA256 56da6fa3c7d28cf023d585606e13f7e4e72a77fa86cb3ffce861fcc0d6aa2fa2
MD5 75d84cf82120baba2ae027a85dd571d0
BLAKE2b-256 36656f6f60292fe590ff33ba9008750699c52167ac9f4cd3fa5c634ace8f6db5

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