# Forgejo Authentication Methods

> **Server**: Forgejo 14.0.4 (Gitea 1.22.0 compatible) at `https://git.cleverthis.com`
> **API Base**: `https://git.cleverthis.com/api/v1`

Forgejo supports multiple authentication methods depending on the endpoint and use case. This document provides an overview of each method and guidance on when to use which.

---

## Authentication Methods

### 1. Personal Access Token (PAT) Authentication

The primary and recommended method for programmatic API access. Tokens are passed via the `Authorization` header.

```bash
curl -s "${FORGEJO_URL}/api/v1/user" \
  -H "Authorization: token ${FORGEJO_PAT}"
```

Alternatively, tokens can be passed as a query parameter (less secure, avoid in production):

```bash
curl -s "${FORGEJO_URL}/api/v1/user?token=${FORGEJO_PAT}"
```

**Use for**: All standard REST API operations — repositories, issues, pull requests, organizations, users, etc.

**See**: [tokens.md](tokens.md) for full details on creating and managing PATs.

---

### 2. Basic Authentication

Uses a username and password pair encoded in the request. Required for token management endpoints.

```bash
curl -s "${FORGEJO_URL}/api/v1/users/${FORGEJO_USERNAME}/tokens" \
  -u "${FORGEJO_USERNAME}:${FORGEJO_PASSWORD}"
```

**Important**: The token management endpoints (`/users/{username}/tokens`) **require basic auth**. You cannot use a PAT to list, create, or delete tokens — this is by design so that token operations are gated by the actual account credentials.

**Use for**:
- Listing existing tokens: `GET /users/{username}/tokens`
- Creating new tokens: `POST /users/{username}/tokens`
- Deleting tokens: `DELETE /users/{username}/tokens/{token}`
- Bootstrap scenarios where no token exists yet

---

### 3. OAuth2 Bearer Token Authentication

Used with OAuth2 access tokens obtained through the OAuth2 authorization flow. Passed via the standard `Authorization: Bearer` header.

```bash
curl -s "${FORGEJO_URL}/api/v1/user" \
  -H "Authorization: Bearer ${OAUTH2_ACCESS_TOKEN}"
```

**Use for**: Third-party application integrations that use the OAuth2 authorization code flow or client credentials flow. Appropriate when building apps that act on behalf of users.

**See**: [oauth2.md](oauth2.md) for OAuth2 application management and flow details.

---

### 4. Web Session Authentication (Cookie + CSRF)

A cookie-based flow that mimics browser login. Required for accessing web-only features that have no REST API equivalent.

```bash
# 1. Fetch login page and extract CSRF token
COOKIE_JAR="/tmp/forgejo-cookies-$$.txt"
LOGIN_PAGE=$(curl -sS -c "$COOKIE_JAR" "${FORGEJO_URL}/user/login")
CSRF=$(echo "$LOGIN_PAGE" | grep -oP 'name="_csrf"\s+content="\K[^"]+')

# 2. Submit login form
curl -sS -L -c "$COOKIE_JAR" -b "$COOKIE_JAR" \
  --data-urlencode "_csrf=${CSRF}" \
  --data-urlencode "user_name=${FORGEJO_USERNAME}" \
  --data-urlencode "password=${FORGEJO_PASSWORD}" \
  "${FORGEJO_URL}/user/login"

# 3. Access web-only resources with session cookie
curl -sS -b "$COOKIE_JAR" "${FORGEJO_URL}/{owner}/{repo}/actions/runs/{run_id}"

# 4. Clean up
rm -f "$COOKIE_JAR"
```

**Use for**: Accessing resources only available through the web UI — most notably **CI/Actions run logs**, which are not exposed through the REST API.

**See**: [web-login.md](web-login.md) for the full CSRF login flow and cookie management.

---

## Comparison Table

| Method | Header / Mechanism | Best For | Limitations |
|---|---|---|---|
| **PAT (Token)** | `Authorization: token ${FORGEJO_PAT}` | All standard API calls | Cannot manage tokens themselves; scoped by token permissions |
| **Basic Auth** | `-u "${USER}:${PASS}"` | Token management endpoints | Exposes password in each request; not suitable for general use |
| **OAuth2 Bearer** | `Authorization: Bearer ${TOKEN}` | Third-party app integrations | Requires OAuth2 app setup and authorization flow |
| **Web Session** | Cookie jar + CSRF token | Web-only features (CI logs) | Complex flow; session can expire; not a stable API contract |

---

## Which Authentication Should I Use?

### Decision Flow

1. **Are you making standard API calls?** (repos, issues, PRs, orgs, users, etc.)
   → Use **PAT authentication**. It is the simplest and most reliable method.

2. **Do you need to create, list, or delete access tokens?**
   → Use **basic authentication**. Token endpoints require username/password credentials.

3. **Are you building a third-party application that acts on behalf of users?**
   → Use **OAuth2**. Register an OAuth2 application and implement the authorization code flow.

4. **Do you need to access CI/Actions logs or other web-only features?**
   → Use **web session authentication**. Perform the CSRF login flow and use session cookies.

---

## Common Patterns

### Verify Authentication Works

```bash
# Test PAT authentication — returns your user profile
curl -s "${FORGEJO_URL}/api/v1/user" \
  -H "Authorization: token ${FORGEJO_PAT}" | jq .login

# Test basic auth — list your tokens
curl -s "${FORGEJO_URL}/api/v1/users/${FORGEJO_USERNAME}/tokens" \
  -u "${FORGEJO_USERNAME}:${FORGEJO_PASSWORD}" | jq '.[].name'
```

### Bootstrap: Create Your First Token with Basic Auth

If you do not yet have a PAT, create one using basic auth:

```bash
curl -s -X POST "${FORGEJO_URL}/api/v1/users/${FORGEJO_USERNAME}/tokens" \
  -u "${FORGEJO_USERNAME}:${FORGEJO_PASSWORD}" \
  -H "Content-Type: application/json" \
  -d '{"name": "{token_name}", "scopes": ["all"]}' | jq .sha1
```

The response `sha1` field contains the token value. Store it securely — it is only shown once at creation time.

---

## Security Notes

- **Never commit tokens or passwords** to version control.
- **Use environment variables** (`FORGEJO_PAT`, `FORGEJO_USERNAME`, `FORGEJO_PASSWORD`) for credentials.
- **Prefer PATs over basic auth** for routine API access — tokens can be scoped and revoked independently.
- **Use HTTPS only** — all authentication credentials are transmitted in headers or request bodies and must be encrypted in transit.
- **Rotate tokens periodically** and use the minimum scopes necessary.
- **Clean up cookie jars** immediately after web session use to prevent session hijacking.

---

## Multi-Identity Authentication

In automated workflows, you often need multiple bot identities. For example:
- **Bot A** creates PRs → uses `${BOT_PAT}`
- **Bot B** reviews PRs → uses `${REVIEWER_PAT}`

This ensures branch protection rules that require "approval from someone other than the PR author" are satisfied.

Each PAT corresponds to a different Forgejo user account. Simply swap the `Authorization` header:

```bash
# Bot A creates the PR
curl -s -X POST ... -H "Authorization: token ${BOT_PAT}"

# Bot B approves the PR (different identity)
curl -s -X POST ... -H "Authorization: token ${REVIEWER_PAT}"
```

See `references/complex-workflows/tips-and-patterns.md` for more examples.
