# Authentication

## Segmind Cloud Authentication Documentation

### Overview

This document details the authentication methods supported by Segmind Platform:

* OAuth 2.0 social login (Google, Microsoft, Discord)
* Bearer token authentication using JWT
* API key authentication for server-to-server communication

Social logins provide a seamless and secure authentication experience by leveraging existing accounts from trusted providers, eliminating the need for users to create and remember additional credentials.

JSON Web Tokens (JWT) are compact, URL-safe tokens that enable secure information transmission between parties, containing encoded JSON payloads that can include user data and permissions.

### OAuth Authentication

#### Supported Providers and Scopes

| Provider  | Required Scopes                 |
| --------- | ------------------------------- |
| Google    | `email`, `profile`              |
| Microsoft | `user.read`, `profile`, `email` |
| Discord   | `identify`, `email`, `guilds`   |

####

### OAuth Login Process

1. Redirect users to our OAuth login page:

```
https://cloud.segmind.com/auth/login
```

2. Users will be redirected to the selected provider's login page. After successful authentication, they'll be returned to:

```
https://cloud.segmind.com/api/login/{provider}/authorized
```

3. Upon successful authentication, you'll receive:

```json
{
  "access_token": "eyJhbGciOiJIUzI1NiIs...",
  "refresh_token": "eyJhbGciOiJIUzI1NiIs...",
  "expires_in": 3600
}
```

The access token thus generated is automatically stored in an HTTP-only secure cookie with a 30-day expiration period. This cookie is used for subsequent API requests and authentication verification.

### Bearer Token Authentication

#### Using Bearer Tokens

Include the JWT token in your API requests using the Authorization header:

```bash
curl -X GET "https://cloud.segmind.com/api/v1/models" \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIs..."
```

#### Token Format

Our JWTs include:

* `jti`: Unique identifier for the JWT
* `exp`: Token expiration timestamp
* `iat`: Token issue timestamp
* `nbf`: Token not valid before timestamp
* `identity`: Email of the token user

#### Token Renewal

To refresh an expired access token:

```bash
curl -X POST "https://cloud.segmind.com/auth/refresh" \
  -H "Authorization: Bearer {refresh_token}"
```

### API Key Authentication

#### Overview

API keys provide server-to-server authentication for automated workflows. Include them in the `x-api-key` request header.

#### API Key Format

* Format: 32-character alphanumeric string
* Prefix: `SG_` for all API keys
* Example: `SG_3ec0a235721add59`

#### Using API Keys

Include the API key in your requests:

```bash
curl -X GET "https://cloud.segmind.com/api/v1/models" \
  -H "x-api-key: SG_3ec0a235721add59"
```

#### API Key Management

Generate a new API key:

```bash
curl -X POST "https://cloud.segmind.com/api/keys" \
  -H "Authorization: Bearer {your_access_token}" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Production API Key",
    "scopes": ["read:models", "write:inference"]
  }'
```

Revoke an API key:

```bash
curl -X DELETE "https://cloud.segmind.com/api/keys/{key_id}" \
  -H "Authorization: Bearer {your_access_token}"
```

### Security Guidelines

#### Token Lifecycle

* Access tokens expire after 1 hour
* Refresh tokens expire after 30 days
* API keys don't expire but should be rotated regularly

#### Rate Limits

* Authentication endpoints: 5 requests/minute per IP
* Token refresh: 10 requests/hour per user
* API endpoints: Varies by subscription tier

#### Best Practices while using the platform

1. **Secure Storage**
   * Never expose API keys in client-side code
   * Use environment variables for key storage
   * Rotate API keys periodically
2. **Error Handling**
   * Implement retry logic with exponential backoff
   * Handle token expiration gracefully
   * Monitor for suspicious activity on your token/keys in [usage](https://cloud.segmind.com/console/usage) on console.

### Error Responses

Common authentication errors:

```json
{
  "error": "invalid_token",
  "error_description": "Token has expired",
  "status_code": 401
}
```

| Status Code | Error                 | Description                      |
| ----------- | --------------------- | -------------------------------- |
| 401         | `invalid_token`       | Token is invalid or expired      |
| 401         | `invalid_api_key`     | API key is invalid               |
| 403         | `insufficient_scope`  | Token lacks required permissions |
| 429         | `rate_limit_exceeded` | Too many requests                |

### Code Examples

#### Python

```python
import requests

class SegmindClient:
    def __init__(self, api_key=None, access_token=None):
        self.base_url = "https://cloud.segmind.com/api/v1"
        self.headers = {}
        if api_key:
            self.headers["x-api-key"] = api_key
        elif access_token:
            self.headers["Authorization"] = f"Bearer {access_token}"
        
    def get_models(self):
        response = requests.get(
            f"{self.base_url}/models",
            headers=self.headers
        )
        return response.json()
```

#### Node.js

```javascript
const axios = require('axios');

class SegmindClient {
  constructor({ apiKey, accessToken }) {
    this.baseUrl = 'https://cloud.segmind.com/api/v1';
    this.headers = {
      'Content-Type': 'application/json',
      ...(apiKey && { 'x-api-key': apiKey }),
      ...(accessToken && { 'Authorization': `Bearer ${accessToken}` })
    };
  }

  async getModels() {
    const response = await axios.get(`${this.baseUrl}/models`, {
      headers: this.headers
    });
    return response.data;
  }
}
```

### Support

For authentication issues or questions:

* Email: <support@segmind.com>
* Documentation: <https://docs.segmind.com>
* Status page: <https://status.segmind.com>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.segmind.com/readme/authentication.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
