> For the complete documentation index, see [llms.txt](https://doc.ozforensics.com/oz-knowledge-ru/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://doc.ozforensics.com/oz-knowledge-ru/rukovodstva/rukovodstvo-razrabotchika/sdk/oz-mobile-sdk/android/podklyuchenie-k-api.md).

# Подключение к API

Для авторизации в Oz API используйте адрес API и [токен доступа](/oz-knowledge-ru/rukovodstva/rukovodstvo-razrabotchika/api/oz-api/autentifikaciya-i-obrabotka-dannykh/tokens.md), как показано ниже.

{% tabs %}
{% tab title="Kotlin" %}

```kotlin
OzLivenessSDK.setApiConnection(OzConnection.fromServiceToken(host, token))
```

{% endtab %}

{% tab title="Java" %}

```java
OzLivenessSDK.INSTANCE.setApiConnection(
        OzConnection.Companion.fromServiceToken(host, token), 
        null
);
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
Мы рекомендуем:

* Указывать адрес API в вашем приложении на экране, предшествующем проверке Liveness. После установки адреса происходит служебный вызов API, и если вы устанавливаете адрес при запуске или инициализации приложения, нагрузка на сервер может быть слишком высокой.
* Убедиться, что перед вызовом метода `createStartIntent` вы инициализировали SDK и подключили его к API. Порядок действий значения не имеет, но они должны успешно завершиться к моменту начала работы `createStartIntent`.
  {% endhint %}

Второй вариант: логин и пароль.

{% tabs %}
{% tab title="Kotlin" %}

```kotlin
OzLivenessSDK.setApiConnection(
    OzConnection.fromCredentials(host, username, password),
    statusListener(
        { token -> /* токен */ },
        { ex -> /* ошибка */ }
    )
)
```

{% endtab %}

{% tab title="Java" %}

```java
OzLivenessSDK.INSTANCE.setApiConnection(
        OzConnection.Companion.fromCredentials(host, username, password),
        new StatusListener<String>() {
            @Override
            public void onStatusChanged(@Nullable String s) {}
            @Override
            public void onSuccess(String token) { /* токен */ }
            @Override
            public void onError(@NonNull OzException e) { /* ошибка */ }
        }
);
```

{% endtab %}
{% endtabs %}

Мы рекомендуем использовать метод аутентификации по токену доступа, как более безопасный.

По умолчанию логи сохраняются вместе с данными по анализам. Если вы планируете хранить логи отдельно от этих данных, настройте отдельное подключение для [телеметрии](/oz-knowledge-ru/other/faq.md#chto-takoe-telemetriya-i-zachem-ee-podklyuchat):

{% tabs %}
{% tab title="Kotlin" %}

```kotlin
OzLivenessSDK.setEventsConnection(
    OzConnection.fromCredentials(
        "https://<link>.ozforensics.com",
        "<your_telemetry_user_eg_tm@company.com>",
        "your_telemetry_password"
    )
)
```

{% endtab %}

{% tab title="Java" %}

```java
OzLivenessSDK.setEventsConnection(
        OzConnection.fromCredentials(
                "https://<link>.ozforensics.com",
                "<your_telemetry_user_eg_tm@company.com>",
                "your_telemetry_password"
        )
);
```

{% endtab %}
{% endtabs %}

Очистка авторизации:

{% tabs %}
{% tab title="Kotlin" %}

```kotlin
OzLivenessSDK.setApiConnection(null)
```

{% endtab %}

{% tab title="Java" %}

```java
OzLivenessSDK.INSTANCE.setApiConnection(null, null);
```

{% endtab %}
{% endtabs %}

Проверка наличия сохраненного access-токена Oz API:

{% tabs %}
{% tab title="Kotlin" %}

```kotlin
val isLoggedIn = OzLivenessSDK.isLoggedIn
```

{% endtab %}

{% tab title="Java" %}

```java
boolean isLoggedIn = OzLivenessSDK.INSTANCE.isLoggedIn();
```

{% endtab %}
{% endtabs %}

LogOut:

{% tabs %}
{% tab title="Kotlin" %}

```kotlin
OzLivenessSDK.logout()
```

{% endtab %}

{% tab title="Java" %}

```java
OzLivenessSDK.INSTANCE.logout();
```

{% endtab %}
{% endtabs %}


---

# 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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://doc.ozforensics.com/oz-knowledge-ru/rukovodstva/rukovodstvo-razrabotchika/sdk/oz-mobile-sdk/android/podklyuchenie-k-api.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
