> For the complete documentation index, see [llms.txt](https://docs.cybus.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.cybus.io/access/security/json-web-tokens.md).

# JSON Web Tokens

Generate long-lived JSON Web Tokens (JWT) to authenticate API requests and automate tasks in Connectware.

JSON Web Tokens (JWT) allow you to authenticate API requests, automate tasks, and securely access Connectware resources. These tokens can be configured as long-lived tokens that remain valid for extended periods, making them ideal for ongoing automation and continuous system access. Learn how to generate tokens, apply security best practices, and understand the protections built into Connectware's authentication system.

## Token Security

Protect your authentication tokens through secure configuration and applying best practices.

### Token Redirection Rules

Connectware enforces strict URL redirection rules to prevent phishing attempts and protect against web security vulnerabilities.

1. **Protocol binding:** Connectware requires HTTPS and ensures that no redirects can downgrade the connection to HTTP.
2. **Domain restriction:** Redirects are limited to the current domain.
   * Example: When accessing `https://demo.cybus.io/`, you can only redirect to paths within that domain. Redirects to external domains like `https://cybus.io/` are blocked.

{% hint style="warning" %}
JSON web tokens provide access to Connectware with the same permissions as the user who generated it. Tokens should be generated by users with only the required permission levels.
{% endhint %}

### Token Best Practices

Implementing secure token practices is crucial for maintaining the security of your Connectware environment. Below are key practices to follow when working with tokens:

1. **Set appropriate expiration**
   * Configure token lifetime using the `expireTimeInHours` parameter based on your specific use case.
   * Avoid unnecessarily long expiration periods.
2. **Implement token rotation**
   * Replace active tokens regularly with new ones: create a new long-lived token, switch your clients to it, then revoke the old token. See [Managing Long-Lived Tokens](#managing-long-lived-tokens).
3. **Separate token usage**
   * Create distinct tokens for different services or tasks.
   * This limits potential security exposure if any single token is compromised.

## Generating JSON Web Tokens

The user needs the **Token** [authentication method](https://docs.cybus.io/access/user-management/users.md#authentication-methods). Without it, `POST /api/login` still returns a token, but every request that uses the token fails with `401 Unauthorized`. See [Enabling Token Authentication for a User](#enabling-token-authentication-for-a-user).

1. Send a POST request to obtain your token. The response will contain a token property with your JWT authentication credentials.

{% code lineNumbers="true" %}

```bash
curl -k -X POST "https://${CONNECTWARE_HOST}/api/login" \
  --header "Content-Type: application/json" \
  --data '{
    "username": "${CONNECTWARE_USERNAME}",
    "password": "${CONNECTWARE_PASSWORD}",
    "expireTimeInHours": 720,
    "label": "dashboard-token"
  }'
```

{% endcode %}

* `${CONNECTWARE_HOST}`: The hostname or IP address of your Connectware installation.
* `${CONNECTWARE_USERNAME}` and `${CONNECTWARE_PASSWORD}`: The credentials of the user who owns the token.

The request body sets these token properties:

* `expireTimeInHours`: How long the token stays valid, in hours.
* `label`: Optional. A name that marks the token as a long-lived token, so that you can list and revoke it later. The label must be unique across all users. If another token already uses it, Connectware returns `409 Conflict` and creates no token.

{% hint style="warning" %}
Connectware returns the token only in this response and does not keep a copy. Store it securely right away. If you lose it, create a new token and revoke the old one, which you find by its label in the [token list](#listing-long-lived-tokens).
{% endhint %}

2. Use this token in subsequent requests by adding it as an `apiToken` query string parameter in your URLs.

{% code lineNumbers="true" %}

```bash
curl -k "https://${CONNECTWARE_HOST}/api/users?apiToken=${TOKEN}"
```

{% endcode %}

Replace `${TOKEN}` with the token from the previous step.

## Managing Long-Lived Tokens

You can list and revoke the long-lived tokens of a user, that is the tokens created with a `label`. The examples use these placeholders:

* `${CONNECTWARE_HOST}`: The hostname or IP address of your Connectware installation.
* `${TOKEN}`: A valid token that authenticates the request, for example one from `POST /api/login`.
* `${USER_ID}`: The ID of the user who created the tokens, as returned by `GET /api/users`.

### Listing Long-Lived Tokens

Send a GET request to `/api/users/${USER_ID}/tokens`:

{% code lineNumbers="true" %}

```bash
curl -k "https://${CONNECTWARE_HOST}/api/users/${USER_ID}/tokens" \
  --header "Authorization: Bearer ${TOKEN}"
```

{% endcode %}

The response lists each long-lived token with its `token_id`, `label`, `created_at`, and `expires_at`. It never contains the token itself. If the user has no long-lived tokens, Connectware returns `404 Not Found`.

### Revoking Long-Lived Tokens

To revoke one token, send a DELETE request with its `token_id` as the `tokenId` query parameter:

{% code lineNumbers="true" %}

```bash
curl -k -X DELETE "https://${CONNECTWARE_HOST}/api/users/${USER_ID}/tokens?tokenId=${TOKEN_ID}" \
  --header "Authorization: Bearer ${TOKEN}"
```

{% endcode %}

Replace `${TOKEN_ID}` with the `token_id` from the token list. Without the `tokenId` parameter, the request revokes all long-lived tokens of the user.

### Logging Out with a Token

To revoke a token that you hold, including a token without a label, send it in the body of a POST request to `/api/logout`:

{% code lineNumbers="true" %}

```bash
curl -k -X POST "https://${CONNECTWARE_HOST}/api/logout" \
  --header "Content-Type: application/json" \
  --data '{ "token": "${TOKEN}" }'
```

{% endcode %}

Connectware revokes the token only if it is the complete, valid token. Otherwise, it returns `404 Not Found`.

## Enabling Token Authentication for a User

Users that you create in the Admin UI have the **Token** authentication method by default. To add it to an existing user in the Admin UI, see [Changing Authentication Methods](https://docs.cybus.io/access/user-management/users.md#changing-authentication-methods).

When you create a user through `POST /api/users`, the user gets only the methods that you list in the `grantTypes` property, and none if you leave it out. Include `token`, and set `isRequired` to `false` so that either method on its own is enough to authenticate:

{% code lineNumbers="true" %}

```json
{
  "username": "api-client",
  "password": "${PASSWORD}",
  "identityProvider": "local",
  "grantTypes": [
    { "method": "password", "isRequired": false },
    { "method": "token", "isRequired": false }
  ]
}
```

{% endcode %}

Replace `${PASSWORD}` with the password for the new user.

To update an existing user through the API, send the same `grantTypes` list with `PUT /api/users/${USER_ID}`, where `${USER_ID}` is the ID of the user. The list replaces all existing methods of the user, so include every method that the user needs.

## Browser Authentication via JSON Web Tokens

You can use tokens to authenticate users via an authentication URL or redirect users to a specific location within Connectware after authentication.

* **Authentication URL:** To authenticate users on the browser using the token, enter the following URL:

{% code lineNumbers="true" %}

```
https://${CONNECTWARE_HOST}/admin?apiToken=${TOKEN}
```

{% endcode %}

* **Authentication with Redirection:** To redirect users to a specific location within Connectware after authentication, enter the following URL. This is particularly useful when working with [Cybus::IngressRoute](https://docs.cybus.io/data-flows/service-commissioning-files/resources/cybus-ingressroute.md) resources.

{% code lineNumbers="true" %}

```
https://${CONNECTWARE_HOST}/admin?redirect=${REDIRECTION_URL}&apiToken=${TOKEN}
```

{% endcode %}

Replace `${REDIRECTION_URL}` with the path within Connectware to open after authentication.

**Example**

{% code lineNumbers="true" %}

```
https://${CONNECTWARE_HOST}/admin?redirect=/services/foo/bar&apiToken=${TOKEN}
```

{% endcode %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

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

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.cybus.io/access/security/json-web-tokens.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
