Authentication overview

Authentication for accessing Brazil's official government information and public services, particularly through the gov.br platform, centers on robust identity verification. The primary goal is to ensure that only authorized entities and individuals can interact with sensitive public data and services. This approach is fundamental for maintaining the integrity and security of government digital offerings. Developers integrating with gov.br APIs will primarily encounter two main authentication paradigms: digital certificates issued under the ICP-Brasil infrastructure and the Gov.br unified account for single sign-on (SSO) contexts.

The choice of authentication method often depends on the specific API or service being accessed, with higher-security operations typically requiring digital certificates. Brazil's digital government strategy emphasizes a unified, secure access point for citizens and businesses, which translates into standardized authentication protocols for API consumers. Understanding these methods is crucial for building reliable and compliant applications that interact with the Brazilian public sector.

Supported authentication methods

The Brazilian government's digital services primarily support two main authentication methods for API access and user (citizen/business) identification:

  • Digital Certificates (ICP-Brasil): These are cryptographic certificates issued under the Brazilian Public Key Infrastructure (Infraestrutura de Chaves Públicas Brasileira - ICP-Brasil). They provide a high level of assurance for identity verification and non-repudiation. Digital certificates are commonly used for signing electronic documents, accessing specific government portals, and securing API communications where strong identity proof is required. They comply with the X.509 standard for public key certificates, as defined by the IETF RFC 5280.
  • Gov.br Account (Unified Access): The Gov.br account serves as a single sign-on (SSO) mechanism for accessing various government digital services. Users can create an account and elevate their security level (Bronze, Silver, Gold) based on the strength of identity verification. For developers, this often translates to using OAuth 2.0 or OpenID Connect flows, where the Gov.br platform acts as the identity provider. The security level of the Gov.br account dictates the range and sensitivity of services an authenticated user can access.

The following table summarizes these methods:

Method When to use Security Level
Digital Certificates (ICP-Brasil) High-security API access, digital signatures, legal validity, automated system-to-system integrations. High (identity verified by a trusted Certificate Authority)
Gov.br Account (SSO) User-driven API access, web/mobile application integration where users log in via Gov.br, access to general public services. Varies (Bronze, Silver, Gold, depending on verification rigor)

Getting your credentials

The process for obtaining credentials depends on the chosen authentication method:

For Digital Certificates (ICP-Brasil)

  1. Choose a Certifying Authority (AC): Select an AC accredited by ICP-Brasil. A list of accredited ACs is available on the official ICP-Brasil website.
  2. Request the Certificate: Follow the chosen AC's procedure, which typically involves submitting documentation (e.g., identity documents, company registration for legal entities) and undergoing face-to-face or video verification.
  3. Install the Certificate: Once issued, the digital certificate (A1, A3, or A4 type) needs to be installed on your computer or smart card/token, depending on its type. This credential is then used by your application or system for authentication.
  4. API Key/Client ID (if applicable): Some specific gov.br APIs might require an additional API key or Client ID in conjunction with the digital certificate for service registration. Consult the specific API documentation for details.

For Gov.br Account (Unified Access)

  1. Create a Gov.br Account: Register for an account on the Acesso.gov.br portal.
  2. Elevate Security Level: To access more sensitive services, you will need to increase your account's security level (from Bronze to Silver or Gold). This involves additional identity verification steps, such as facial recognition via the Gov.br app, banking institution validation, or validation with an ICP-Brasil digital certificate.
  3. Register Your Application: For applications intending to use the Gov.br account for user authentication (e.g., via OAuth 2.0), you typically need to register your application with the Gov.br developer portal (if available for your specific use case). This registration will provide you with a Client ID and Client Secret.
  4. Implement OAuth 2.0/OpenID Connect Flow: Your application will then initiate an OAuth 2.0 authorization code flow, redirecting users to the Gov.br login page. Upon successful authentication, Gov.br redirects the user back to your application with an authorization code, which you exchange for an access token and potentially an ID token.

Authenticated request example

Due to the diverse nature of gov.br APIs and their authentication mechanisms (digital certificates vs. Gov.br account SSO), a single universal example is not feasible. However, we can illustrate conceptual examples for both primary methods.

Example with Digital Certificate (Conceptual)

When using a digital certificate, the authentication typically happens at the TLS layer (mTLS) or by digitally signing the request payload. For HTTP requests, this often involves configuring your HTTP client to use the client-side certificate. The exact implementation depends on your programming language and HTTP client library.

import requests

# Assuming 'cert.pem' contains your client certificate and 'key.pem' your private key
# In a real scenario, these would be securely managed, e.g., from an HSM or secure store.
cert_path = ('/path/to/your/cert.pem', '/path/to/your/key.pem')

api_endpoint = "https://api.gov.br/sensitive-service/data"
headers = {
    "Accept": "application/json",
    # Additional headers might be required by the specific API
}

try:
    response = requests.get(api_endpoint, headers=headers, cert=cert_path, verify=True)
    response.raise_for_status() # Raise an exception for HTTP errors
    print(response.json())
except requests.exceptions.RequestException as e:
    print(f"An error occurred: {e}")

In this Python example, the cert parameter in the requests.get call instructs the client to present the specified digital certificate during the TLS handshake, authenticating the client to the API server.

Example with Gov.br Account (OAuth 2.0 Access Token - Conceptual)

After a user has authenticated via the Gov.br portal and your application has exchanged the authorization code for an access token, you would typically use this token in the Authorization header for subsequent API calls.

GET /userinfo HTTP/1.1
Host: api.gov.br
Authorization: Bearer YOUR_GOVBR_ACCESS_TOKEN
Accept: application/json
async function fetchUserInfo(accessToken) {
  const response = await fetch('https://api.gov.br/userinfo', {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${accessToken}`,
      'Accept': 'application/json'
    }
  });

  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }
  return await response.json();
}

// Example usage (assuming accessToken is already obtained)
// fetchUserInfo(myAccessToken).then(data => console.log(data));

This JavaScript example demonstrates how an obtained OAuth 2.0 access token is included in the Authorization: Bearer header to authenticate requests to a Gov.br API endpoint.

Security best practices

Adhering to security best practices is paramount when integrating with Brazil's government APIs:

  • Secure Credential Storage: Never hardcode API keys, client secrets, or digital certificate private keys directly into your application code. Use environment variables, secure configuration files, or dedicated secret management services (e.g., AWS Secrets Manager, Google Secret Manager, Azure Key Vault) to store sensitive credentials.
  • Protect Private Keys: For digital certificates, ensure that the private key is never exposed or transmitted over insecure channels. Use hardware security modules (HSMs) or secure tokens for storing and using private keys when possible.
  • Implement OAuth 2.0 Securely: When using the Gov.br account with OAuth 2.0, always use the Authorization Code Flow with PKCE (Proof Key for Code Exchange) for public clients (e.g., mobile apps, SPAs) to mitigate interception attacks. Validate redirect URIs strictly and ensure state parameters are used to prevent CSRF attacks. The OAuth 2.0 PKCE specification provides detailed guidance.
  • Least Privilege Principle: Request only the minimum necessary scopes or permissions when initiating OAuth 2.0 flows. For system-to-system integrations, ensure the digital certificate or API key used has only the permissions required for its specific function.
  • Input Validation and Output Encoding: Always validate all input received from API responses and user interactions to prevent injection attacks (e.g., SQL injection, XSS). Properly encode all output displayed to users to mitigate XSS vulnerabilities.
  • Error Handling: Implement robust error handling without revealing sensitive information in error messages. Generic error messages are preferable in production environments.
  • Regular Audits and Monitoring: Continuously monitor your application's logs for unusual authentication attempts or API access patterns. Regularly audit your security configurations and update dependencies to patch known vulnerabilities.
  • Keep Up-to-Date: Stay informed about the latest security recommendations from the Brazilian government (e.g., via the ICP-Brasil website) and general web security best practices.