> For the complete documentation index, see [llms.txt](https://developer.harness.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developer.harness.io/artifact-registry/3.0/agents/authentication-for-agents.md).

# Authentication for agents

Create Harness Artifacts service account tokens, assign minimal permissions, store credentials securely in CI and Kubernetes, and rotate tokens without downtime.

Non-interactive agents, such as AI coding assistants, CI/CD pipelines, Kubernetes workloads, and scheduled jobs, cannot authenticate through a browser. This page covers the credential types available, how to create them, how to store them securely in common environments, and how to rotate them without causing downtime.

## Token types

Harness issues two token types. Use the right one for the right context.

|                 | Personal Access Token (PAT)         | Service Account Token                        |
| --------------- | ----------------------------------- | -------------------------------------------- |
| **Tied to**     | A human user identity               | A machine identity                           |
| **Use for**     | Local development, one-time scripts | CI/CD, Kubernetes, all automation            |
| **Breaks when** | The user leaves or is deactivated   | Never (unless explicitly revoked)            |
| **Permissions** | Inherit the user's RBAC             | Defined independently on the service account |
| **Audit log**   | Shows the user's email              | Shows the service account name               |

**Rule**: any token used in automation must be a service account token. PATs in pipelines create a hidden dependency on a human account.

***

## Create a service account

Service accounts live at the account, org, or project level. Create them at the lowest scope that covers the registries your agent needs to access.

1. **Open service accounts**. In the Harness UI, go to **Account Settings** (or **Org Settings** / **Project Settings** for a narrower scope) and select **Service Accounts**.
2. **Create the account**. Select **New Service Account**. Give it a name that describes the workload, for example, `ci-push-prod` or `deploy-agent-staging`. The identifier is auto-generated from the name.
3. **Generate a token**. Open the service account, select **Tokens**, then **New Token**. Set an expiry that fits your rotation schedule (90 days is a reasonable default for CI tokens). Copy the token value; it is shown only once.
4. **Assign roles**. Select **Role Bindings**, then **New Role Binding**. Assign the token the minimum role it needs. Go to [Minimal permission sets](#minimal-permission-sets) for the minimum role required.

{% hint style="warning" %}
**Token value shown once**

Harness does not store the raw token. If you close the dialog before copying, you must generate a new token. Store it in a secrets manager immediately.
{% endhint %}

***

## Credential format

Every Harness registry client uses the same credential pair:

| Field                          | Value                           |
| ------------------------------ | ------------------------------- |
| **Username** (service account) | `_token`                        |
| **Password**                   | The service account token value |
| **Username** (PAT)             | Your Harness account email      |
| **Password**                   | The PAT value                   |
| **HTTP header** (REST API)     | `x-api-key: <token>`            |

```bash
# Service account: username is the literal string "_token"
docker login pkg.harness.io \
  --username _token \
  --password "$HARNESS_API_KEY"

# PAT: username is the email address
docker login pkg.harness.io \
  --username "you@example.com" \
  --password "$HARNESS_API_KEY"
```

***

## Minimal permission sets

Grant only what the agent needs. These are the common patterns:

| Agent role                                    | Built-in role to assign                                          |
| --------------------------------------------- | ---------------------------------------------------------------- |
| Read artifacts, pull images                   | Artifact Registry Viewer                                         |
| Push artifacts (CI build output)              | Artifact Registry Contributor                                    |
| Manage registries (create, configure, delete) | Artifact Registry Admin                                          |
| Approve Dependency Firewall exceptions        | Custom role requiring the Firewall Exceptions Approve permission |

Apply the role at the **project scope** if the registry lives in a project, the **org scope** if shared across projects, or the **account scope** if shared across the whole organization. A service account with project-scoped permissions cannot access registries in other projects.

Go to [RBAC and permissions](https://developer.harness.io/artifact-registry/3.0/reference/rbac-and-permissions.md) for exact permission identifiers and the full role reference.

***

## Store credentials in CI environments

Never put a token in source code or a Dockerfile. Store it in the secret mechanism of your CI system and inject it as an environment variable.

### GitHub Actions

Add `HARNESS_API_KEY`, `HARNESS_ACCOUNT_ID`, and `HARNESS_EMAIL` as repository or organization secrets (**Settings > Secrets and variables > Actions**), then reference them in your workflow:

```yaml
jobs:
  build-and-push:
    runs-on: ubuntu-latest
    steps:
      - name: Log in to Harness Artifacts
        run: |
          echo "$HARNESS_API_KEY" | docker login pkg.harness.io \
            --username _token \
            --password-stdin
      - name: Push image
        run: |
          docker push "pkg.harness.io/$HARNESS_ACCOUNT_ID/my-registry/my-app:${{ github.sha }}"
    env:
      HARNESS_API_KEY: ${{ secrets.HARNESS_API_KEY }}
      HARNESS_ACCOUNT_ID: ${{ secrets.HARNESS_ACCOUNT_ID }}
```

### GitLab CI

Add variables in **Settings > CI/CD > Variables** with the **Masked** flag set, then reference them:

```yaml
build:
  script:
    - echo "$HARNESS_API_KEY" | docker login pkg.harness.io --username _token --password-stdin
    - docker push "pkg.harness.io/$HARNESS_ACCOUNT_ID/my-registry/my-app:$CI_COMMIT_SHA"
  variables:
    HARNESS_API_KEY: $HARNESS_API_KEY     # from CI/CD variables
    HARNESS_ACCOUNT_ID: $HARNESS_ACCOUNT_ID
```

### Jenkins

Store the token as a **Secret text** credential in **Manage Jenkins > Credentials**, then inject it with `withCredentials`:

```groovy
pipeline {
  agent any
  environment {
    HARNESS_ACCOUNT_ID = 'your-account-id'   // non-sensitive; set directly or via a build parameter
  }
  stages {
    stage('Push') {
      steps {
        withCredentials([string(credentialsId: 'harness-api-key', variable: 'HARNESS_API_KEY')]) {
          sh '''
            echo "$HARNESS_API_KEY" | docker login pkg.harness.io \
              --username _token --password-stdin
            docker push "pkg.harness.io/${HARNESS_ACCOUNT_ID}/my-registry/my-app:${BUILD_NUMBER}"
          '''
        }
      }
    }
  }
}
```

### Kubernetes secrets

Store the token as a Kubernetes Secret to avoid putting it in environment variables that might appear in pod logs:

```bash
kubectl create secret generic harness-ar-token \
  --from-literal=api-key="$HARNESS_API_KEY" \
  --namespace my-namespace
```

Reference it in a pod spec as an environment variable from the secret:

```yaml
env:
  - name: HARNESS_API_KEY
    valueFrom:
      secretKeyRef:
        name: harness-ar-token
        key: api-key
```

***

## Kubernetes imagePullSecrets

For Kubernetes to pull container images from a private Harness registry, create an `imagePullSecret` in each namespace where workloads run.

**Create the secret**:

```bash
kubectl create secret docker-registry harness-ar \
  --docker-server=pkg.harness.io \
  --docker-username=_token \
  --docker-password="$HARNESS_API_KEY" \
  --namespace=my-namespace
```

**Reference in a pod spec**:

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: my-app
spec:
  containers:
    - name: my-app
      image: pkg.harness.io/<ACCOUNT_ID>/<REGISTRY>/my-app:latest
  imagePullSecrets:
    - name: harness-ar
```

**Reference in a Deployment**:

```yaml
spec:
  template:
    spec:
      imagePullSecrets:
        - name: harness-ar
      containers:
        - name: my-app
          image: pkg.harness.io/<ACCOUNT_ID>/<REGISTRY>/my-app:v1.2.3
```

**Attach to a ServiceAccount** so all pods using that account inherit it automatically:

```bash
kubectl patch serviceaccount default \
  -p '{"imagePullSecrets": [{"name": "harness-ar"}]}' \
  --namespace my-namespace
```

{% hint style="info" %}
Create the `imagePullSecret` in every namespace where your workloads run. Kubernetes secrets are namespace-scoped and cannot be shared across namespaces without being recreated.
{% endhint %}

***

## Token rotation

Tokens should be rotated before they expire. The recommended pattern is to generate the replacement before revoking the old token so there is no downtime.

**Zero-downtime rotation**:

1. **Generate a new token**. In Harness, open the service account and generate a new token. Leave the old token active.
2. **Update the secret in your environment**. Update the secret value in your CI system, Kubernetes secret, or secrets manager with the new token. Trigger a test run to confirm the new token works.
3. **Revoke the old token**. Once the new token is confirmed working, delete the old token from the service account. Any agent still using the old token will start receiving `401` errors, which surfaces stale credentials.

**Rotation frequency recommendations**:

| Use case                   | Recommended rotation                                                |
| -------------------------- | ------------------------------------------------------------------- |
| Production CI/CD pipeline  | Every 90 days                                                       |
| Kubernetes imagePullSecret | Every 180 days (or align with cluster cert rotation)                |
| Short-lived agent sessions | Generate per-session, expire after 24h                              |
| Developer workstation      | Scoped tokens from Setup Client (30–180 days), regenerate on expiry |

**Automate rotation with a scheduled job**:

{% hint style="warning" %}
**Verify the API endpoint before use**

The token-generation endpoint in this section follows the Harness NextGen platform API pattern. Confirm the exact path, `<SA_ID>` format, and response field against the [Harness API Reference](https://apidocs.harness.io/) before running this in production. If `NEW_TOKEN` is empty, the `kubectl apply` will overwrite the secret with a blank password, breaking image pulls.
{% endhint %}

```bash
#!/bin/bash
# Generate a new token via the Harness API, update the Kubernetes secret,
# then revoke the old token. Run on a cron schedule.

NEW_TOKEN=$(curl -s -X POST \
  -H "x-api-key: $HARNESS_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"name":"ci-token-rotated","validTo":<expiry_epoch_ms>}' \
  "https://app.harness.io/ng/api/serviceaccount/<SA_ID>/token?accountIdentifier=$HARNESS_ACCOUNT_ID" \
  | jq -r '.data.token')

# Guard: abort if token was not retrieved
if [ -z "$NEW_TOKEN" ] || [ "$NEW_TOKEN" = "null" ]; then
  echo "ERROR: failed to retrieve new token" >&2
  exit 1
fi

kubectl create secret docker-registry harness-ar \
  --docker-server=pkg.harness.io \
  --docker-username=_token \
  --docker-password="$NEW_TOKEN" \
  --namespace=my-namespace \
  --dry-run=client -o yaml | kubectl apply -f -
```

***

## Troubleshooting

<details>

<summary>401 Unauthorized: token looks correct but every request fails</summary>

Check whether the token was generated from **Setup Client** (scoped token with a user-selected expiry) or from **Account Settings > API Keys** (configurable expiry). Setup Client tokens are scoped to a single registry and expire after the duration selected at generation, so they cannot authenticate against a different registry or the management API.

Run this to verify the token is accepted at all:

```bash
curl -s -o /dev/null -w "%{http_code}" \
  -H "x-api-key: $HARNESS_API_KEY" \
  "https://app.harness.io/har/api/v1/registry?accountIdentifier=$HARNESS_ACCOUNT_ID"
```

Expected: `200`. If you get `401`, the token is wrong or expired.

</details>

<details>

<summary>403 Forbidden: token is valid but operations are denied</summary>

The service account does not have the required permission at the scope where the registry lives. Common causes:

* The registry is at the **org** scope but the service account has permissions at the **project** scope only.
* The service account has **View** permission but the pipeline is trying to push (requires **Create/Edit**).
* The pipeline runs on a schedule or webhook and uses the service account identity, but the service account was never assigned a role.

Go to **Account Settings > Service Accounts > \[account] > Role Bindings** and confirm the role and scope.

</details>

<details>

<summary>Kubernetes pods stuck in ImagePullBackOff</summary>

The pod cannot pull the image. Confirm:

1. The `imagePullSecret` exists in the same namespace as the pod: `kubectl get secret harness-ar -n <namespace>`
2. The secret has not expired: `kubectl get secret harness-ar -n <namespace> -o jsonpath='{.data.\.dockerconfigjson}' | base64 -d | jq '.auths'`
3. The pod spec references the secret by its exact name.
4. The service account token inside the secret has the **View** permission on the registry.

</details>

<details>

<summary>Pipeline passes on manual trigger, fails 403 on schedule</summary>

Manual runs use the triggering user's permissions. Scheduled runs use the service account or bot principal configured for the pipeline. That principal has not been assigned the View or Push permission on the registry.

Go to the pipeline's service account and add an **Artifact Registry Viewer** or **Artifact Registry Contributor** role binding at the correct scope.

</details>

<details>

<summary>imagePullSecret works in one namespace but not another</summary>

Kubernetes secrets are namespace-scoped. Recreate the secret in each namespace:

```bash
kubectl create secret docker-registry harness-ar \
  --docker-server=pkg.harness.io \
  --docker-username=_token \
  --docker-password="$HARNESS_API_KEY" \
  --namespace=other-namespace
```

</details>

***

## Next steps

* [Using Artifacts with AI agents](https://developer.harness.io/artifact-registry/3.0/agents/using-ar-with-ai-agents.md): URL patterns, core operations, and REST API reference
* [API quickstart for agents](https://developer.harness.io/artifact-registry/3.0/agents/api-quickstart-for-agents.md): full per-format push/pull commands
* [RBAC and permissions](https://developer.harness.io/artifact-registry/3.0/reference/rbac-and-permissions.md): full permission and role reference
* [Environment variables](https://developer.harness.io/artifact-registry/3.0/reference/environment-variables.md): all credential variables used across clients

{% @harness-feedback/feedback %}
