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.3.tar.gz (17.2 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.3-py3-none-any.whl (16.3 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: govbr_auth-0.1.3.tar.gz
  • Upload date:
  • Size: 17.2 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.3.tar.gz
Algorithm Hash digest
SHA256 8c31a0827b109376fe5dd2816fcadf1615173437b7194340d42cef353e37ffe5
MD5 32fa4d19112e6dc1d914c863b00258a2
BLAKE2b-256 81bb2b7d3fa4889e36b2a741e3731a5e44f4b50a527c9d8331cb5e6448906f2e

See more details on using hashes here.

File details

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

File metadata

  • Download URL: govbr_auth-0.1.3-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.3

File hashes

Hashes for govbr_auth-0.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 c3da668e550eb298b30e5bece6bce47e3ae6d484118e763f2720d01251894443
MD5 5fcdbd13d0449cafa466105ad56507be
BLAKE2b-256 cc2956350a944ea7f62ea21b03ef29d32e34141a9f12e64d312e8112e3e88659

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