> ## Documentation Index
> Fetch the complete documentation index at: https://developer.buildpass.global/llms.txt
> Use this file to discover all available pages before exploring further.

# Authentication

> To interact with the BuildPass API, you need to authenticate using OAuth 2.0.

The BuildPass API uses **OAuth 2.0** for authentication, fully compliant with RFC 6749. We support two authentication flows:

## Authentication Flows

### Client Credentials Grant (Server-to-Server)

For **server-to-server integrations** without user involvement, use the Client Credentials flow. This is ideal for backend services that need to access BuildPass data programmatically.

👉 **This page documents the Client Credentials flow.**

### Authorization Code Grant (User Authorization)

For **applications that need user consent** and access to data on behalf of specific builders, use the Authorization Code flow with PKCE.

<Card title="OAuth 2.0 Authorization Code Flow" icon="user-check" href="/features/oauth-authorization-code">
  Learn about user authorization with PKCE for integrator applications.
</Card>

***

## Client Types

BuildPass supports two types of OAuth 2.0 clients, each designed for different security requirements:

### Confidential Clients

**Confidential clients** can securely store credentials and are required to authenticate with a `client_secret`.

**Best for:**

* Backend services and servers
* Server-to-server integrations
* Applications running in secure, controlled environments
* Services where credentials can be kept private

**Authentication:** Must provide both `client_id` and `client_secret` to obtain access tokens.

### Public Clients

**Public clients** cannot securely store credentials (e.g., mobile apps, single-page applications) and can authenticate without a `client_secret`.

**Best for:**

* Mobile applications (iOS, Android)
* Single-page applications (SPAs)
* Desktop applications
* Browser-based applications

**Authentication:** Only requires `client_id`. Must use PKCE (Proof Key for Code Exchange) with the Authorization Code flow for security.

<Note>
  Your client type is determined when BuildPass provisions your integration credentials. Contact BuildPass support if you need to change your client type or are unsure which type you have.
</Note>

***

## Client Credentials Grant

This flow provides secure, token-based authentication for server-to-server integrations.

<Warning>
  **Client Credentials Grant is only available for Confidential Clients.** Public clients must use the [Authorization Code flow with PKCE](/features/oauth-authorization-code).
</Warning>

### Step 1: Obtain Client Credentials

You need to have the following client credentials:

* `client_id`
* `client_secret`

These credentials should be provided by BuildPass. If you don't have them, please contact BuildPass support.

### Step 2: Generate an OAuth Token

To generate an OAuth token, you need to make a POST request to the `/oauth/token` endpoint with your client credentials. The request body should include the following parameters:

* `client_id`: Your client ID.
* `client_secret`: Your client secret.
* `scope`: The scopes you want to request access to. Available scopes include `read:builders`, `read:subcontractors`, `read:prequalifications`, `read:insurances`, `read:contacts`, `read:swms`, `read:timesheets`, `read:inductions`.
* `audience`: The audience for the token. This should be set to `https://api.buildpass.global`.
* `grant_type`: The grant type you want to use. This should be set to `client_credentials`.

<Note>
  Use `https://api.buildpass.global` as both the OAuth host and token audience for External API integrations. Regional MCP connector hosts use a different OAuth resource model and are not a replacement for the External API integration audience.
</Note>

{" "}

<Card title="API reference" icon="shield" href="/api-reference/authentication/post">
  Check out the API reference for our OAuth2 token endpoint.
</Card>

#### Example Request

```bash theme={null}
curl --request POST \
  --url https://api.buildpass.global/oauth/token \
  --header 'Content-Type: application/json' \
  --data '{
  "client_id": "your_client_id",
  "client_secret": "your_client_secret",
  "scope": "read:builders read:subcontractors read:prequalifications read:insurances",
  "audience": "https://api.buildpass.global",
  "grant_type": "client_credentials"
}'
```

#### Alternative: HTTP Basic Authentication

You can also provide client credentials via HTTP Basic Authentication instead of the request body:

```bash theme={null}
curl --request POST \
  --url https://api.buildpass.global/oauth/token \
  --header 'Content-Type: application/json' \
  --header 'Authorization: Basic base64(client_id:client_secret)' \
  --data '{
  "scope": "read:builders read:subcontractors",
  "audience": "https://api.buildpass.global",
  "grant_type": "client_credentials"
}'
```

#### Form Data Support

The endpoint also supports `application/x-www-form-urlencoded` content type:

```bash theme={null}
curl --request POST \
  --url https://api.buildpass.global/oauth/token \
  --header 'Content-Type: application/x-www-form-urlencoded' \
  --data 'client_id=your_client_id&client_secret=your_client_secret&scope=read:builders&audience=https://api.buildpass.global&grant_type=client_credentials'
```

#### Response Format

The token response follows OAuth 2.0 standards:

```json theme={null}
{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "expires": 3600 // deprecated, please use expires_in,
  "scope": "read:builders read:subcontractors"
}
```

#### Error Responses

Error responses follow OAuth 2.0 RFC 6749 standards:

```json theme={null}
{
  "error": "invalid_client",
  "error_description": "Invalid client credentials"
}
```

Common error codes:

* `invalid_request`: Missing or malformed request parameters
* `invalid_client`: Invalid client credentials
* `invalid_scope`: Requested scopes are invalid for the audience
* `unsupported_grant_type`: Grant type not supported

### Step 3: Use the Access Token

Once you have the access token, include it in the Authorization header of your API requests as a Bearer token.

#### Example Authorization Header

```
Authorization: Bearer YOUR_ACCESS_TOKEN
```

## OAuth 2.0 Compliance Features

Our implementation is fully compliant with OAuth 2.0 standards:

### RFC 6749 - OAuth 2.0 Authorization Framework

* ✅ **Client Credentials Grant** (Section 4.4)
* ✅ **Standard Token Response Format** (Section 5.1)
* ✅ **Standard Error Response Format** (Section 5.2)
* ✅ **Client Authentication Methods** (Section 2.3.1)

### RFC 6750 - Bearer Token Usage

* ✅ **Authorization Request Header Field** (Section 2.1)
* ✅ **Cache Control Headers** (Section 3)

### Additional Security Features

* ✅ **JWT Access Tokens** with HMAC-SHA256 signing
* ✅ **Unique Token IDs** (jti claim) for token tracking
* ✅ **Encrypted Client Secret Storage**
* ✅ **Audience-Specific Scope Validation**
* ✅ **Comprehensive Audit Logging**

### Token Management

* **Token Lifetime**: 1 hour (3600 seconds)
* **Token Format**: JSON Web Token (JWT)
* **Signing Algorithm**: HMAC-SHA256
* **Security Headers**: Cache-Control: no-store, Pragma: no-cache

## Token Security Best Practices

### Credential Storage

<Warning>
  **Critical Security Requirements:**
</Warning>

1. **Encrypt client secrets at rest** - Never store in plain text or environment variables visible in logs
2. **Use secure credential management** - Consider using secret managers (AWS Secrets Manager, HashiCorp Vault, etc.)
3. **Encrypt access tokens at rest** - Use your platform's secure storage
4. **Never log credentials or tokens** - Treat them as sensitive data
5. **Rotate credentials periodically** - Contact BuildPass support for credential rotation

### Token Handling

```javascript theme={null}
// ✅ GOOD: Secure credential storage (Node.js example)
const AWS = require('aws-sdk');
const secretsManager = new AWS.SecretsManager();

async function getCredentials() {
  const secret = await secretsManager.getSecretValue({
    SecretId: 'buildpass/client-credentials'
  }).promise();
  return JSON.parse(secret.SecretString);
}

// ❌ BAD: Never do this
const CLIENT_SECRET = process.env.CLIENT_SECRET; // Visible in logs
console.log('Secret:', CLIENT_SECRET); // Never log secrets!
```

### Access Token Storage

For applications that cache access tokens:

```javascript theme={null}
// ✅ GOOD: In-memory storage with expiration tracking
class TokenManager {
  constructor() {
    this.token = null;
    this.expiresAt = null;
  }

  async getToken() {
    if (this.token && Date.now() < this.expiresAt) {
      return this.token;
    }
    return await this.refreshToken();
  }

  async refreshToken() {
    const response = await fetchNewToken();
    this.token = response.access_token;
    this.expiresAt = Date.now() + (response.expires_in * 1000);
    return this.token;
  }
}

// ❌ BAD: Never store tokens in files or databases without encryption
fs.writeFileSync('token.txt', accessToken); // Insecure!
```

### Network Security

1. **Always use HTTPS** - BuildPass API only accepts HTTPS connections
2. **Validate TLS certificates** - Don't disable certificate validation
3. **Use Basic Auth header** - Preferred method for client credentials
4. **Don't include credentials in URLs** - Use headers or request body

### Monitoring and Auditing

BuildPass provides comprehensive audit logging:

* All token requests are logged with client ID and IP address
* Failed authentication attempts are tracked
* Unusual patterns trigger alerts

We recommend:

* Monitor your token usage patterns
* Set up alerts for failed authentication attempts
* Regularly review access logs
* Investigate unexpected token requests
