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

# Authentication

> Learn how to authenticate with the Gitea API using tokens, basic auth, and OAuth2

## Overview

Gitea API supports multiple authentication methods to secure access to your resources. The recommended method is using personal access tokens with the Authorization header.

## Authentication Methods

Gitea supports the following authentication methods:

1. **Authorization Header Token** (Recommended)
2. **HTTP Basic Authentication**
3. **OAuth2**
4. **Query Parameters** (Deprecated)

## Personal Access Tokens

### Creating a Token

Personal access tokens are the recommended way to authenticate with the Gitea API.

1. Log in to your Gitea instance
2. Navigate to **Settings** → **Applications** → **Access Tokens**
3. Click **Generate New Token**
4. Enter a token name and select the required scopes
5. Click **Generate Token**
6. Copy the token immediately (it won't be shown again)

<Warning>
  Store your access tokens securely. They provide the same level of access as your password for the scopes you've granted.
</Warning>

### Using Tokens in Requests

The recommended way to use tokens is via the `Authorization` header with the `token` prefix:

<CodeGroup>
  ```bash cURL theme={null}
  curl -H "Authorization: token YOUR_TOKEN" \
    https://your-gitea-instance.com/api/v1/user
  ```

  ```javascript JavaScript (Fetch) theme={null}
  fetch('https://your-gitea-instance.com/api/v1/user', {
    headers: {
      'Authorization': 'token YOUR_TOKEN'
    }
  })
  .then(response => response.json())
  .then(data => console.log(data));
  ```

  ```python Python (Requests) theme={null}
  import requests

  headers = {
      'Authorization': 'token YOUR_TOKEN'
  }

  response = requests.get(
      'https://your-gitea-instance.com/api/v1/user',
      headers=headers
  )
  print(response.json())
  ```

  ```go Go theme={null}
  package main

  import (
      "fmt"
      "net/http"
      "io/ioutil"
  )

  func main() {
      client := &http.Client{}
      req, _ := http.NewRequest("GET", "https://your-gitea-instance.com/api/v1/user", nil)
      req.Header.Add("Authorization", "token YOUR_TOKEN")
      
      resp, _ := client.Do(req)
      defer resp.Body.Close()
      
      body, _ := ioutil.ReadAll(resp.Body)
      fmt.Println(string(body))
  }
  ```
</CodeGroup>

### Token Scopes

Tokens can be created with specific scopes to limit their permissions:

| Scope Category      | Read                | Write                | Description             |
| ------------------- | ------------------- | -------------------- | ----------------------- |
| `repo`              | `read:repository`   | `write:repository`   | Access to repositories  |
| `admin:org`         | `read:organization` | `write:organization` | Organization management |
| `admin:public_key`  | `read:public_key`   | `write:public_key`   | SSH key management      |
| `admin:repo_hook`   | `read:repo_hook`    | `write:repo_hook`    | Repository webhooks     |
| `admin:org_hook`    | -                   | `write:org_hook`     | Organization webhooks   |
| `admin:user_hook`   | -                   | `write:user_hook`    | User webhooks           |
| `notification`      | `read:notification` | `write:notification` | Notifications           |
| `user`              | `read:user`         | `write:user`         | User information        |
| `admin:gpg_key`     | `read:gpg_key`      | `write:gpg_key`      | GPG key management      |
| `admin:application` | `read:application`  | `write:application`  | OAuth2 applications     |
| `package`           | `read:package`      | `write:package`      | Package registry        |
| `admin:misc`        | -                   | `write:misc`         | Miscellaneous admin     |
| `activitypub`       | `read:activitypub`  | `write:activitypub`  | ActivityPub federation  |

<Note>
  The API automatically determines the required access level (read/write) based on the HTTP method. GET requests require read access, while POST/PUT/PATCH/DELETE require write access.
</Note>

### Public-Only Scopes

Tokens can be restricted to public resources only by appending `:public` to the scope:

* `read:repository:public` - Only access public repositories
* `read:organization:public` - Only access public organizations
* `read:user:public` - Only access public user information

## HTTP Basic Authentication

Basic authentication uses your Gitea username and password (or token).

<CodeGroup>
  ```bash Username and Password theme={null}
  curl -u username:password \
    https://your-gitea-instance.com/api/v1/user
  ```

  ```bash Token as Password theme={null}
  curl -u username:YOUR_TOKEN \
    https://your-gitea-instance.com/api/v1/user
  ```

  ```bash Token as Username theme={null}
  curl -u YOUR_TOKEN:x-oauth-basic \
    https://your-gitea-instance.com/api/v1/user
  ```
</CodeGroup>

<Warning>
  HTTP Basic Authentication is supported but not recommended for API usage. Use personal access tokens with the Authorization header instead.
</Warning>

### Two-Factor Authentication (2FA)

If two-factor authentication is enabled on your account, include the TOTP code in the `X-GITEA-OTP` header:

```bash theme={null}
curl -u username:password \
  -H "X-GITEA-OTP: 123456" \
  https://your-gitea-instance.com/api/v1/user
```

## OAuth2 Authentication

Gitea supports OAuth2 for third-party application authentication.

### Creating an OAuth2 Application

1. Go to **Settings** → **Applications** → **OAuth2 Applications**
2. Click **Create a new OAuth2 Application**
3. Enter application details and redirect URI
4. Note the Client ID and Client Secret

### OAuth2 Flow

1. **Authorization Request**:

```
GET https://your-gitea-instance.com/login/oauth/authorize?
  client_id=CLIENT_ID&
  redirect_uri=REDIRECT_URI&
  response_type=code&
  state=RANDOM_STATE
```

2. **Token Exchange**:

```bash theme={null}
curl -X POST https://your-gitea-instance.com/login/oauth/access_token \
  -H "Content-Type: application/json" \
  -d '{
    "client_id": "CLIENT_ID",
    "client_secret": "CLIENT_SECRET",
    "code": "AUTHORIZATION_CODE",
    "grant_type": "authorization_code",
    "redirect_uri": "REDIRECT_URI"
  }'
```

3. **Use Access Token**:

```bash theme={null}
curl -H "Authorization: Bearer ACCESS_TOKEN" \
  https://your-gitea-instance.com/api/v1/user
```

<Note>
  OAuth2 tokens are JWT (JSON Web Tokens) and contain a dot (`.`) in the token string.
</Note>

## Query Parameter Authentication (Deprecated)

<Warning>
  Query parameter authentication is deprecated and will be removed in Gitea 1.23. Migrate to Authorization header authentication.
</Warning>

Historically, tokens could be passed as query parameters:

```bash theme={null}
# Using 'token' parameter (deprecated)
curl https://your-gitea-instance.com/api/v1/user?token=YOUR_TOKEN

# Using 'access_token' parameter (deprecated)
curl https://your-gitea-instance.com/api/v1/user?access_token=YOUR_TOKEN
```

If query parameter authentication is disabled via `DISABLE_QUERY_AUTH_TOKEN=true`, these requests will fail with a warning in the server logs.

## Sudo / Impersonation

Administrators can perform API requests on behalf of other users using the sudo feature.

### Using Sudo Header

```bash theme={null}
curl -H "Authorization: token ADMIN_TOKEN" \
  -H "Sudo: target-username" \
  https://your-gitea-instance.com/api/v1/user
```

### Using Sudo Query Parameter

```bash theme={null}
curl -H "Authorization: token ADMIN_TOKEN" \
  "https://your-gitea-instance.com/api/v1/user?sudo=target-username"
```

<Warning>
  Sudo functionality requires administrator privileges. Non-admin users will receive a 403 Forbidden error.
</Warning>

## Actions Authentication

Gitea Actions workflows can authenticate using automatic task tokens:

```yaml theme={null}
steps:
  - name: Call API
    run: |
      curl -H "Authorization: Bearer ${{ secrets.ACTIONS_RUNTIME_TOKEN }}" \
        https://your-gitea-instance.com/api/v1/repos/${{ github.repository }}
```

Task tokens are:

* Automatically generated for running workflows
* Scoped to the repository where the action is running
* Valid only while the task is in "running" status

## Testing Authentication

Test your authentication by retrieving your user information:

<CodeGroup>
  ```bash Test Token theme={null}
  curl -H "Authorization: token YOUR_TOKEN" \
    https://your-gitea-instance.com/api/v1/user
  ```

  ```json Success Response theme={null}
  {
    "id": 1,
    "login": "username",
    "email": "user@example.com",
    "full_name": "User Name",
    "avatar_url": "https://your-gitea-instance.com/avatars/1"
  }
  ```

  ```json Error Response (401) theme={null}
  {
    "message": "token is required"
  }
  ```
</CodeGroup>

## Security Best Practices

<CardGroup cols={2}>
  <Card title="Use HTTPS" icon="lock">
    Always use HTTPS in production to prevent token interception
  </Card>

  <Card title="Scope Tokens" icon="shield">
    Grant minimal necessary scopes to access tokens
  </Card>

  <Card title="Rotate Tokens" icon="rotate">
    Regularly rotate tokens and revoke unused ones
  </Card>

  <Card title="Secure Storage" icon="vault">
    Never commit tokens to version control or expose in logs
  </Card>
</CardGroup>

## Managing Tokens via API

You can manage access tokens programmatically:

### List Tokens

```bash theme={null}
curl -u username:password \
  https://your-gitea-instance.com/api/v1/users/username/tokens
```

### Create Token

```bash theme={null}
curl -u username:password \
  -H "Content-Type: application/json" \
  -X POST \
  -d '{"name":"my-token","scopes":["read:repository","write:repository"]}' \
  https://your-gitea-instance.com/api/v1/users/username/tokens
```

### Delete Token

```bash theme={null}
curl -u username:password \
  -X DELETE \
  https://your-gitea-instance.com/api/v1/users/username/tokens/TOKEN_ID
```

<Note>
  Creating and deleting tokens requires Basic Authentication or Reverse Proxy authentication. You cannot use a token to create another token.
</Note>

## Troubleshooting

### 401 Unauthorized

* Verify the token is correct and not expired
* Check that the token hasn't been revoked
* Ensure you're using the correct authentication method

### 403 Forbidden

* Verify the token has the required scopes
* Check if the account is active and not prohibited from login
* Ensure 2FA requirements are met if enforced
* For sudo requests, verify admin privileges

### Deprecation Warnings

If you see `X-Gitea-Warning` headers about deprecated authentication:

```
X-Gitea-Warning: token and access_token API authentication is deprecated
```

Migrate to using the Authorization header:

```bash theme={null}
# Instead of:
curl "https://your-gitea-instance.com/api/v1/user?token=YOUR_TOKEN"

# Use:
curl -H "Authorization: token YOUR_TOKEN" \
  https://your-gitea-instance.com/api/v1/user
```

## Next Steps

<CardGroup cols={2}>
  <Card title="API Reference" icon="book" href="/api-reference">
    Explore available API endpoints
  </Card>

  <Card title="Webhooks" icon="webhook" href="/essentials/webhooks">
    Set up webhooks for event notifications
  </Card>
</CardGroup>
