> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/cvat-ai/cvat/llms.txt
> Use this file to discover all available pages before exploring further.

# Authentication

> Authentication methods and configuration for self-hosted CVAT

CVAT supports multiple authentication methods for self-hosted deployments, providing flexibility for different organizational requirements.

## Authentication Methods

CVAT implements the following authentication methods defined in `cvat/settings/base.py:136-141`:

1. **Token Authentication**: API token-based authentication
2. **Access Token Authentication**: Bearer token authentication
3. **Session Authentication**: Cookie-based session authentication
4. **Basic Authentication**: HTTP Basic authentication

## Default Authentication Backends

Configured in `cvat/settings/base.py:250-253`:

```python theme={null}
AUTHENTICATION_BACKENDS = [
    "django.contrib.auth.backends.ModelBackend",
    "allauth.account.auth_backends.AuthenticationBackend",
]
```

### Django Model Backend

The default Django authentication backend that authenticates against the PostgreSQL database using username/email and password.

### Django-allauth Backend

Provides advanced authentication features including:

* Email verification
* Social authentication support
* Account management

See `cvat/settings/base.py:255-263` for allauth configuration.

## REST API Authentication

REST API authentication classes defined in `cvat/settings/base.py:136-141`:

```python theme={null}
"DEFAULT_AUTHENTICATION_CLASSES": [
    "rest_framework.authentication.TokenAuthentication",
    "cvat.apps.access_tokens.authentication.AccessTokenAuthentication",
    "rest_framework.authentication.SessionAuthentication",
    "cvat.apps.iam.authentication.BasicAuthenticationEx",
]
```

### Token Authentication

Django REST Framework's built-in token authentication. Users receive a token upon login that must be included in the `Authorization` header:

```bash theme={null}
Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
```

### Access Token Authentication

Custom bearer token authentication for API access tokens. Implemented in `cvat/apps/access_tokens/authentication.py:11-27`.

Tokens are passed in the `Authorization` header:

```bash theme={null}
Authorization: Bearer <access_token>
```

Key features:

* Validates token against the database
* Checks user active status
* Updates last use timestamp
* Raises `AuthenticationFailed` for invalid or expired tokens

### Session Authentication

Cookie-based authentication for web browsers. Sessions are stored in Redis and managed by Django.

Session configuration in `cvat/settings/base.py:423`:

```python theme={null}
CSRF_COOKIE_NAME = "csrftoken"
```

### Basic Authentication Extended

Custom implementation in `cvat/apps/iam/authentication.py:12-26` that extends Django REST Framework's BasicAuthentication with email verification:

```python theme={null}
class BasicAuthenticationEx(BasicAuthentication):
    def authenticate(self, request):
        result = super().authenticate(request)
        
        if (
            allauth_settings.EMAIL_VERIFICATION
            == allauth_settings.EmailVerificationMethod.MANDATORY
            and result
        ):
            user = result[0]
            if not EmailAddress.objects.is_verified(user.email):
                raise exceptions.AuthenticationFailed("E-mail is not verified.")
        
        return result
```

## Account Configuration

Account authentication settings in `cvat/settings/base.py:256-263`:

```python theme={null}
ACCOUNT_EMAIL_VERIFICATION = "none"  # Options: "none", "optional", "mandatory"
ACCOUNT_AUTHENTICATION_METHOD = "username_email"  # Users can login with username or email
ACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = "/auth/email-confirmation"
ACCOUNT_EMAIL_VERIFICATION_SENT_REDIRECT_URL = "/auth/email-verification-sent"
INCORRECT_EMAIL_CONFIRMATION_URL = "/auth/incorrect-email-confirmation"
```

### Username Requirements

Defined in `cvat/settings/base.py:693`:

```python theme={null}
ACCOUNT_USERNAME_MIN_LENGTH = 5
ACCOUNT_LOGOUT_ON_PASSWORD_CHANGE = True
```

## Email Verification

Email verification can be configured to:

* **none**: No email verification required (default)
* **optional**: Email verification is optional
* **mandatory**: Email must be verified before access is granted

To enable email verification, you need to configure email settings. See the Email Configuration section below.

### Email Configuration Example

Create a custom settings file based on `cvat/settings/email_settings.py:1-17`:

```python theme={null}
from cvat.settings.production import *

# Enable email verification
ACCOUNT_AUTHENTICATION_METHOD = "username_email"
ACCOUNT_CONFIRM_EMAIL_ON_GET = True
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_EMAIL_VERIFICATION = "mandatory"

# Configure email backend (example for SMTP)
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "smtp.gmail.com"
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = "your-email@gmail.com"
EMAIL_HOST_PASSWORD = "your-app-password"
DEFAULT_FROM_EMAIL = "your-email@gmail.com"
```

Note: By default, `EMAIL_BACKEND` is set to `None` in `cvat/settings/base.py:754`, which will raise an error if email functionality is needed without proper configuration.

## Identity and Access Management (IAM)

IAM settings in `cvat/settings/base.py:223-233`:

```python theme={null}
IAM_TYPE = "BASIC"  # Options: "BASIC", "LDAP"
IAM_DEFAULT_ROLE = "user"
IAM_ADMIN_ROLE = "admin"
IAM_ROLES = ["admin", "user", "worker"]  # Ordered by priority
IAM_OPA_HOST = "http://opa:8181"
IAM_OPA_DATA_URL = f"{IAM_OPA_HOST}/v1/data"
LOGIN_URL = "rest_login"
LOGIN_REDIRECT_URL = "/"
```

### User Roles

Three built-in roles with descending priority:

1. **admin**: Full system access
2. **user**: Standard user access
3. **worker**: Limited access for annotation workers

## Password Validation

Password validators defined in `cvat/settings/base.py:397-410`:

```python theme={null}
AUTH_PASSWORD_VALIDATORS = [
    {"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"},
    {"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"},
    {"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"},
    {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},
]
```

## Login URLs and Redirects

Defined in `cvat/settings/base.py:233-234`:

```python theme={null}
LOGIN_URL = "rest_login"
LOGIN_REDIRECT_URL = "/"
```

## Open Policy Agent (OPA)

CVAT uses OPA for authorization decisions. Configuration in `docker-compose.yml:313-330`:

```yaml theme={null}
cvat_opa:
  container_name: cvat_opa
  image: openpolicyagent/opa:1.12.2
  command:
    - run
    - --server
    - --addr=:8181
    - --set=services.cvat.url=http://cvat-server:8080
    - --set=bundles.cvat.service=cvat
    - --set=bundles.cvat.resource=/api/auth/rules
```

The OPA server fetches authorization rules from the CVAT server at `/api/auth/rules`.

## API Rate Limiting

Throttle configuration in `cvat/settings/base.py:158-163`:

```python theme={null}
"DEFAULT_THROTTLE_CLASSES": [
    "rest_framework.throttling.AnonRateThrottle",
],
"DEFAULT_THROTTLE_RATES": {
    "anon": "100/minute",
}
```

Anonymous users are limited to 100 requests per minute. Authenticated users have no throttle limit by default.

## Custom Authentication Adapter

Custom account adapter in `cvat/settings/base.py:696`:

```python theme={null}
ACCOUNT_ADAPTER = "cvat.apps.iam.adapters.DefaultAccountAdapterEx"
```

## Security Settings

### HTTPS Configuration

Configured in `cvat/settings/base.py:601-609`:

```python theme={null}
# Trust X-Forwarded-Proto header from proxy
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
SECURE_REFERRER_POLICY = "strict-origin-when-cross-origin"
USE_X_FORWARDED_HOST = True
```

### CORS Configuration

CORS headers defined in `cvat/settings/base.py:585-596`:

```python theme={null}
CORS_ALLOW_HEADERS = list(default_headers) + [
    "upload-offset",
    "upload-length",
    "tus-version",
    "tus-resumable",
    "upload-start",
    "upload-finish",
    "upload-multiple",
    "x-organization",
]
```

## API Documentation

CVAT provides interactive API documentation with authentication support. Configuration in `cvat/settings/base.py:617-689`:

```python theme={null}
SPECTACULAR_SETTINGS = {
    "SERVE_PERMISSIONS": ["rest_framework.permissions.IsAuthenticated"],
    # ...
}
```

Access the API documentation at:

* Swagger UI: `http://your-host:8080/api/docs`
* ReDoc: `http://your-host:8080/api/redoc`
* OpenAPI Schema: `http://your-host:8080/api/schema`

## Next Steps

* [SSO and LDAP Configuration](/self-hosted/admin/sso-ldap) - Enterprise SSO integration
* [Configuration](/self-hosted/admin/configuration) - General configuration options

## Additional Resources

* Source: `cvat/apps/iam/authentication.py`
* Source: `cvat/apps/access_tokens/authentication.py`
* Source: `cvat/settings/base.py:223-263`
* [Django Authentication Documentation](https://docs.djangoproject.com/en/4.2/topics/auth/)
* [Django REST Framework Authentication](https://www.django-rest-framework.org/api-guide/authentication/)
* [Django-allauth Documentation](https://django-allauth.readthedocs.io/)
