Core assíncrono
Configuração
- class govbr_auth.core.GovBrSettings(*, environment: ProviderEnvironment = ProviderEnvironment.PRODUCTION, authorization_url: AnyHttpUrl, token_url: AnyHttpUrl, userinfo_url: AnyHttpUrl, client_id: str, client_secret: SecretStr, redirect_uri: AnyHttpUrl, scope: str = 'openid profile email', transaction_secret: SecretStr, issuer: AnyHttpUrl, jwks_url: AnyHttpUrl, logout_url: AnyHttpUrl | None = None, post_logout_redirect_uri: AnyHttpUrl | None = None, connect_timeout_seconds: Annotated[float, Gt(gt=0)] = 5.0, read_timeout_seconds: Annotated[float, Gt(gt=0)] = 10.0, clock_skew_seconds: Annotated[int, Ge(ge=0)] = 60)[source]
Bases:
BaseModelValidate immutable configuration for a Gov.br OAuth provider.
- model_config = {'extra': 'forbid', 'frozen': True, 'hide_input_in_errors': True, 'str_strip_whitespace': True}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- environment: ProviderEnvironment
- authorization_url: AnyHttpUrl
- token_url: AnyHttpUrl
- userinfo_url: AnyHttpUrl
- client_id: str
- client_secret: SecretStr
- redirect_uri: AnyHttpUrl
- scope: str
- transaction_secret: SecretStr
- issuer: AnyHttpUrl
- jwks_url: AnyHttpUrl
- logout_url: AnyHttpUrl | None
- post_logout_redirect_uri: AnyHttpUrl | None
- connect_timeout_seconds: Annotated[float, Gt(gt=0)]
- read_timeout_seconds: Annotated[float, Gt(gt=0)]
- clock_skew_seconds: Annotated[int, Ge(ge=0)]
- classmethod validate_nonempty_text(value: str) str[source]
Reject empty values needed to create a valid OAuth request.
- classmethod validate_nonempty_secret(value: SecretStr) SecretStr[source]
Reject whitespace-only credentials without exposing their contents.
- validate_url_schemes() GovBrSettings[source]
Require HTTPS except for loopback-only configuration.
- validate_logout_configuration() GovBrSettings[source]
Require a complete, paired logout configuration.
- validate_official_provider_environment() GovBrSettings[source]
Reject official Gov.br endpoints from another deployment.
Cliente e autorização
- class govbr_auth.core.GovBrClient(settings: GovBrSettings, transactions: TransactionCodec, validator: IdTokenValidator, http: AsyncClient)[source]
Bases:
objectCoordinate authorization, token exchange, validation, and userinfo I/O.
- __init__(settings: GovBrSettings, transactions: TransactionCodec, validator: IdTokenValidator, http: AsyncClient) None[source]
Store validated configuration and injected collaborators.
- property settings: GovBrSettings
Expose immutable configuration to framework boundary policies.
- authorization_url(*, now: datetime) AuthorizationRequest[source]
Create an authorization request bound to a protected transaction.
- validate_state(state: str, *, now: datetime) None[source]
Validate a callback state without exchanging an authorization code.
- async exchange_code(*, code: str, state: str, now: datetime) AuthenticationResult[source]
Exchange a one-time authorization transaction for validated tokens.
- class govbr_auth.core.AuthorizationBuilder(settings: GovBrSettings, transactions: TransactionCodec)[source]
Bases:
objectBuild Gov.br OAuth authorization requests bound to protected transactions.
- __init__(settings: GovBrSettings, transactions: TransactionCodec) None[source]
Store the validated provider configuration and transaction collaborator.
AuthorizationBuilder.build_logout() constrói o redirecionamento de logout
usando exclusivamente post_logout_redirect_uri configurado.
- class govbr_auth.core.AuthenticationResult(tokens: TokenSet, id_token_claims: Mapping[str, object])[source]
Bases:
objectReturn validated tokens and a shallowly immutable ID-claim mapping.
The top-level mapping cannot be changed. Nested values retain the mutability provided by the token decoder.
- id_token_claims: Mapping[str, object]
Transações e validação
- class govbr_auth.core.EncryptedTransactionCodec(secret: SecretStr, ttl: timedelta = datetime.timedelta(seconds=300))[source]
Bases:
objectProtect OAuth transactions without retaining process-local state.
- issue(*, now: datetime) tuple[str, AuthTransaction][source]
Create and protect a new OAuth transaction.
- decode(state: str, *, now: datetime) AuthTransaction[source]
Authenticate and decode an OAuth transaction.
- class govbr_auth.core.TransactionCodec(*args, **kwargs)[source]
Bases:
ProtocolDefine stateless OAuth transaction protection operations.
- issue(*, now: datetime) tuple[str, AuthTransaction][source]
Create and protect a new OAuth transaction.
- decode(state: str, *, now: datetime) AuthTransaction[source]
Authenticate and decode an OAuth transaction.
- __init__(*args, **kwargs)
- class govbr_auth.core.IdTokenValidator(*, settings: GovBrSettings)[source]
Bases:
objectValidate signed ID tokens against configured identity and JWKS data.
- __init__(*, settings: GovBrSettings) None[source]
- validate(id_token: SecretStr, expected_nonce: SecretStr, *, jwks: Mapping[str, object], now: datetime) Mapping[str, object][source]
Return verified claims or raise a stable domain error.
- Parameters:
id_token – Compact JWT received from the token endpoint.
expected_nonce – Nonce bound to the originating authorization transaction.
jwks – Provider JSON Web Key Set used for this validation call.
now – Trusted current time used for deterministic temporal validation.
- Returns:
The verified ID token claims.
- Raises:
InvalidIdTokenError – If any cryptographic or claim validation fails.
ValueError – If
nowdoes not carry explicit timezone information.
Modelos
- class govbr_auth.core.AuthTransaction(*, transaction_id: str, code_verifier: SecretStr, nonce: SecretStr, issued_at: datetime, expires_at: datetime)[source]
Bases:
BaseModelStore the short-lived values created for one OAuth authorization flow.
- model_config = {'extra': 'forbid', 'frozen': True}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- transaction_id: str
- code_verifier: SecretStr
- nonce: SecretStr
- issued_at: datetime
- expires_at: datetime
- classmethod validate_transaction_id(value: str) str[source]
Reject blank identifiers that cannot safely bind an OAuth transaction.
- classmethod validate_code_verifier(value: SecretStr) SecretStr[source]
Require the ASCII unreserved verifier syntax defined by RFC 7636.
- classmethod validate_nonce(value: SecretStr) SecretStr[source]
Reject blank nonce secrets without exposing their contents.
- classmethod validate_timezone_aware_datetime(value: datetime) datetime[source]
Reject transaction timestamps that do not carry an explicit timezone.
- validate_expiration() AuthTransaction[source]
Reject transactions whose expiration does not follow their issuance.
- class govbr_auth.core.GovBrUser(*, sub: str, name: str | None = None, social_name: str | None = None, given_name: str | None = None, family_name: str | None = None, middle_name: str | None = None, nickname: str | None = None, preferred_username: str | None = None, profile: str | None = None, picture: str | None = None, website: str | None = None, email: str | None = None, email_verified: bool | None = None, gender: str | None = None, birthdate: str | None = None, zoneinfo: str | None = None, locale: str | None = None, phone_number: str | None = None, phone_number_verified: bool | None = None, address: GovBrAddress | None = None, updated_at: int | None = None)[source]
Bases:
BaseModelRepresent the standard OpenID Connect claims exposed for a Gov.br user.
- model_config = {'extra': 'forbid', 'frozen': True}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- sub: str
- name: str | None
- social_name: str | None
- given_name: str | None
- family_name: str | None
- middle_name: str | None
- nickname: str | None
- preferred_username: str | None
- profile: str | None
- picture: str | None
- website: str | None
- email: str | None
- email_verified: bool | None
- gender: str | None
- birthdate: str | None
- zoneinfo: str | None
- locale: str | None
- phone_number: str | None
- phone_number_verified: bool | None
- address: GovBrAddress | None
- updated_at: int | None
- classmethod validate_subject(value: str) str[source]
Reject blank OpenID Connect subject identifiers.
- property subject: str
Return the stable subject while preserving
subon the wire.
- class govbr_auth.core.TokenSet(*, access_token: SecretStr, id_token: SecretStr, token_type: Literal['Bearer'], expires_in: Annotated[int, Gt(gt=0)], scope: str)[source]
Bases:
BaseModelStore the OAuth tokens returned by a successful authorization flow.
- model_config = {'extra': 'forbid', 'frozen': True}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- access_token: SecretStr
- id_token: SecretStr
- token_type: Literal['Bearer']
- expires_in: Annotated[int, Gt(gt=0)]
- scope: str
Erros públicos
- class govbr_auth.core.GovBrAuthError[source]
Bases:
ExceptionRepresent a Gov.br authentication failure with a stable error code.
- code: str = 'govbr_auth_error'
- class govbr_auth.core.InvalidStateError[source]
Bases:
GovBrAuthErrorRepresent a rejected OAuth state value.
- code: str = 'invalid_state'
- class govbr_auth.core.InvalidIdTokenError[source]
Bases:
GovBrAuthErrorRepresent a rejected OpenID Connect ID token.
- code: str = 'invalid_id_token'