> ## Documentation Index
> Fetch the complete documentation index at: https://www.vobiz.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Sign in with the Vobiz Flutter SDK

> Create a VobizClient, configure it with SdkConfig, and sign in with SIP endpoint credentials, a credentials provider, or a Vobiz access token (JWT). Covers logging, connection state, token renewal, and signing out.

Every app follows the same sequence: create one `VobizClient`, sign in, wait until it is registered, then make and receive calls. This page covers each step.

## Create the client

```dart Signature theme={null}
VobizClient({
  SdkConfig config = const SdkConfig(),
  Logger? logger,
  http.Client? httpClient,
  ConnectivityMonitor? connectivityMonitor,
  AppLifecycleMonitor? lifecycleMonitor,
})
```

| Parameter | Type | Default | Description |
| - | - | - | - |
| `config` | `SdkConfig` | `const SdkConfig()` | Server addresses, reconnection, keep-alive, ICE, and media settings. See [Configuration](#configuration). |
| `logger` | `Logger?` | Logs only when `config.debug` is `true` | Receives every SDK log line. See [Logging](#logging). |
| `httpClient` | `http.Client?` | A client the SDK creates and closes | The HTTP client for backend requests. Pass your own to share connection pools or for tests. |
| `connectivityMonitor` | `ConnectivityMonitor?` | Uses `connectivity_plus` | Reports Wi-Fi, mobile, and offline. Replace it only in tests. |
| `lifecycleMonitor` | `AppLifecycleMonitor?` | Uses Flutter's app lifecycle | Reports foreground and background. Replace it only in tests. |

Create one client for the app session and keep it, for example in your state-management layer. Call `dispose()` when you no longer need it.

```dart theme={null}
final client = VobizClient(
  config: const SdkConfig(debug: true),
);
```

## Configuration

`SdkConfig` holds no credentials. Every field has a default, so `const SdkConfig()` works for most apps.

| Field | Type | Default | Description |
| - | - | - | - |
| `wsUrl` | `String` | `wss://registrar.vobiz.ai:5063/` | WebSocket URL of the Vobiz SIP registrar. |
| `sipServer` | `String` | `registrar.vobiz.ai` | SIP domain used in the `From`, `To`, and `Contact` headers. |
| `autoReconnect` | `bool` | `true` | Reconnect and re-register automatically when the connection drops. |
| `reconnectPolicy` | `ReconnectPolicy` | 1 s doubling to 30 s, 10 attempts | Backoff for `autoReconnect`. See [Network and reconnection](https://www.vobiz.ai/docs/integrations/flutter-sdk/network.md#reconnect-policy). |
| `keepAlive` | `KeepAliveConfig` | WebSocket ping every 15 s | How a dead connection is detected. See [Keep-alive](https://www.vobiz.ai/docs/integrations/flutter-sdk/network.md#keep-alive). |
| `watchNetwork` | `bool` | `true` | React to Wi-Fi, mobile, and offline changes at once: fail calls fast while offline and reconnect as soon as the network returns. |
| `reregisterOnForeground` | `bool` | `true` | Register again each time the app returns to the foreground, so Vobiz has the device's current address. |
| `iceConfig` | `IceConfig` | Google's public STUN server | STUN and TURN servers for call audio. See [TURN](https://www.vobiz.ai/docs/integrations/flutter-sdk/network.md#stun-and-turn). |
| `mediaConstraints` | `MediaConstraints` | Audio only, echo cancellation, noise suppression, auto gain | Microphone settings. See [Microphone settings](https://www.vobiz.ai/docs/integrations/flutter-sdk/network.md#microphone-settings). |
| `debug` | `bool` | `false` | Print SDK log lines with `debugPrint`. |
| `unsafeDemoZeroConfig` | `bool` | `false` | **Demo only.** Allows the methods that send your account Auth Token from the device. See [Demo mode](#demo-mode-zero-config). |
| `backendUrl` | `String` | `https://rtc-demo.vobiz.ai` | **Demo only.** The webhook server used by Zero-Config, transfers, and the recordings list. |
| `voiceApiUrl` | `String` | `https://api.vobiz.ai` | **Demo only.** The Vobiz REST API the webhook server calls. |
| `answerUrl` | `String?` | `null` | Reserved. The SDK doesn't use it: set the Answer URL on the endpoint's [application](https://www.vobiz.ai/docs/platform/voice/applications.md). |

## Logging

Pass `SdkConfig(debug: true)` to print log lines with `debugPrint`, or route them into your own logging:

```dart Signature theme={null}
typedef LogWriter = void Function(String message);

Logger({LogWriter? writer})
```

```dart theme={null}
final client = VobizClient(
  logger: Logger(writer: (line) => debugPrint('VobizSDK $line')),
);
```

Each line starts with `[INFO]`, `[WARN]`, or `[ERROR]`. Log lines can contain phone numbers and SIP usernames, so don't upload them to third-party services without your users' consent.

## Choose a sign-in method

| Method | Use it when | What reaches the device |
| - | - | - |
| [`connectWithCredentials`](#sip-credentials) | Testing, or your app already holds an endpoint's credentials | The endpoint's username and password |
| [`connectWithCredentialsProvider`](#credentials-provider) | Production with one SIP endpoint per user | The endpoint's credentials, fetched from your backend and re-fetched when refused |
| [`connectWithAccessToken`](#access-tokens) / [`connectWithAccessTokenProvider`](#token-provider) | Production without endpoints | A short-lived signed token |
| [`connectWithAuthToken`](#demo-mode-zero-config) | Demos only | Your account Auth ID and Auth Token |

Every sign-in method **completes once the REGISTER request is sent**, not when Vobiz answers it. Watch [`connectionEvents`](#watch-the-connection) for `RegistrationState.registered` before you place a call. Signing in again replaces the current sign-in.

## SIP credentials

Signs in as an existing [SIP endpoint](https://www.vobiz.ai/docs/integrations/flutter-sdk/create-sip-endpoint.md).

```dart Signature theme={null}
Future<void> connectWithCredentials(CredentialConfig config)

const CredentialConfig({
  required String username,
  required String password,
  String? displayName,
  String? answerUrl,
})
```

| Parameter | Type | Description |
| - | - | - |
| `username` | `String` | The endpoint's full SIP username, from the **SIP USERNAME** column in **Voice** > **Endpoints**. |
| `password` | `String` | The endpoint's password. |
| `displayName` | `String?` | Optional display name. |
| `answerUrl` | `String?` | Reserved. Not used. |

**Returns** a `Future` that completes when the REGISTER is sent.

**Errors.** If the WebSocket can't connect, the `Future` throws and `errorEvents` emits `connect_failed`; with `autoReconnect` the SDK keeps retrying. A refused registration doesn't throw: `errorEvents` emits `registration_failed`, and a 403 arrives with the message "Wrong credentials".

```dart theme={null}
Future<void> signInWithEndpoint(VobizClient client) async {
  await client.connectWithCredentials(
    const CredentialConfig(
      username: 'YOUR_SIP_USERNAME',
      password: 'YOUR_SIP_PASSWORD',
    ),
  );
}
```

## Credentials provider

In production your backend creates one endpoint per user, keeps its password, and hands it to the app after authenticating the user with your own session. A credentials provider fetches those credentials, and fetches them again when the registrar refuses them (for example, after your backend rotated the password).

```dart Signature theme={null}
typedef VobizCredentialsProvider =
    Future<CredentialConfig> Function(VobizCredentialsRequest request);

Future<VobizCredentialsSession> connectWithCredentialsProvider(
  VobizCredentialsProvider provider, {
  int maxRefreshes = 1,
})
```

| Parameter | Type | Default | Description |
| - | - | - | - |
| `provider` | `VobizCredentialsProvider` | Required | Returns the signed-in user's endpoint credentials. Throwing, or returning an empty username or password, fails the sign-in. |
| `maxRefreshes` | `int` | `1` | How many times in a row the provider is asked again after a refusal before the session gives up. |

`VobizCredentialsRequest` tells the provider why it is called:

| Value | When | What to return |
| - | - | - |
| `signIn` | The first sign-in. | Cached credentials if you have them; otherwise ask your backend. |
| `rejected` | The registrar refused the last credentials (401 or 403). | Fresh credentials from your backend. Don't return the cache. |
| `refresh` | Your app called `session.refresh()`. | Fresh credentials from your backend. |

**Returns** a `VobizCredentialsSession`:

| Member | Description |
| - | - |
| `Stream<VobizException> failures` | Emits when the session gives up: the provider failed, or `maxRefreshes` refusals in a row. |
| `Future<void> refresh()` | Fetches credentials again with `VobizCredentialsRequest.refresh` and re-registers. |
| `Future<void> dispose()` | Stops watching. Call it at sign-out together with `client.disconnect()`. |
| `VobizClient client` / `int maxRefreshes` | The client and the limit the session was created with. |

**Throws** `VobizCredentialsException` when the provider fails on the first sign-in.

### Fetch credentials from your backend

`VobizBackendCredentialsProvider` is a ready-made provider. It sends `POST <url>` with the JSON body `{"reason": "sign_in" | "rejected" | "refresh"}` and the headers you supply, and expects:

```json theme={null}
{ "sip_username": "YOUR_SIP_USERNAME", "sip_password": "YOUR_SIP_PASSWORD", "display_name": "Asha" }
```

`display_name` is optional. Any other field is ignored.

```dart Signature theme={null}
VobizBackendCredentialsProvider({
  required Uri url,
  FutureOr<Map<String, String>> Function()? headers,
  http.Client? httpClient,
  Duration timeout = const Duration(seconds: 15),
})
```

```dart theme={null}
Future<VobizCredentialsSession> signInFromBackend(VobizClient client) async {
  final provider = VobizBackendCredentialsProvider(
    url: Uri.parse('https://api.example.com/voice/sip-credentials'),
    headers: () async => {'Authorization': 'Bearer YOUR_APP_SESSION_TOKEN'},
  );
  final session = await client.connectWithCredentialsProvider(provider.call);
  session.failures.listen((e) => debugPrint('Sign-in stopped: ${e.message}'));
  return session;
}
```

## Access tokens

An access token is a short-lived JSON Web Token (JWT) that your backend mints for each user. The app registers with the token instead of a password, so **no SIP endpoint has to exist** and no long-lived secret reaches the device.

Your backend mints the token with `POST /api/v1/Account/{auth_id}/JWT/Token/`, authenticated with your account Auth ID and Auth Token, after it has authenticated your app's user.

| Claim | Description |
| - | - |
| `iss` | Your Vobiz Auth ID, such as `MA_XXXXXXXX`. |
| `sub` | Your user's ID. The app registers as `<sub>_<iss>`. |
| `nbf`, `exp` | Validity window in Unix seconds. `exp - nbf` must be between 180 seconds and 24 hours. |
| `per.voice.incoming_allow` | `true` to let the user receive calls. |
| `per.voice.outgoing_allow` | `true` to let the user place calls. Without it, `makeCall` throws. |
| `app` | The ID of the [application](https://www.vobiz.ai/docs/platform/voice/applications.md) whose Answer URL handles the user's outbound calls. |

> [!TIP]
>
> Set `nbf` about 60 seconds in the past: a registrar clock slightly behind your server's otherwise refuses a brand-new token with `10005` (not valid yet). Always include `app`.

To ring a token user, dial `<User>sip:<sub>_<auth_id>@registrar.vobiz.ai</User>` from your application.

### Sign in with a token

```dart Signature theme={null}
Future<void> connectWithAccessToken(String accessToken)
```

| Parameter | Type | Description |
| - | - | - |
| `accessToken` | `String` | A Vobiz access token (JWT) from your backend. |

The client registers as `<sub>_<iss>` and sends the token in an `X-Vobiz-Jwt` header on the REGISTER and on every outbound call. The token is not renewed: once it expires, the next REGISTER is refused with `ACCESS_TOKEN_EXPIRED`. Pass a fresh token to [`updateAccessToken`](#renew-a-token) before then, or use a [token provider](#token-provider).

**Throws** `VobizAccessTokenException` (`INVALID_ACCESS_TOKEN`, 10001) before connecting when the string isn't a Vobiz token. A refusal by the registrar arrives on `errorEvents` as `registration_failed`, with a `VobizAccessTokenException` as its `cause`.

```dart theme={null}
Future<void> signInWithToken(VobizClient client) async {
  await client.connectWithAccessToken('YOUR_ACCESS_TOKEN');
  debugPrint('Registering as ${client.sipUsername}');
}
```

### Token provider

A token provider signs in and keeps the sign-in alive: shortly before each token expires, the SDK asks for a new one and registers with it on the same connection, without touching a call in progress.

```dart Signature theme={null}
typedef VobizAccessTokenProvider =
    Future<String> Function(VobizAccessTokenRequest request);

Future<VobizAccessTokenSession> connectWithAccessTokenProvider(
  VobizAccessTokenProvider provider, {
  Duration refreshBefore = const Duration(seconds: 60),
  int maxRefreshes = 1,
})
```

| Parameter | Type | Default | Description |
| - | - | - | - |
| `provider` | `VobizAccessTokenProvider` | Required | Returns a fresh token. Throwing, or returning an empty string, fails the request. |
| `refreshBefore` | `Duration` | 60 seconds | How long before a token's `exp` to ask for the next one. Renewals are never scheduled sooner than 5 seconds. |
| `maxRefreshes` | `int` | `1` | How many refused tokens in a row before the session gives up. |

| `VobizAccessTokenRequest` | When |
| - | - |
| `signIn` | The first sign-in. |
| `expiring` | The current token expires within `refreshBefore`. |
| `rejected` | The registrar refused the current token. Mint a new one; don't return a cached token. |
| `refresh` | Your app called `session.refresh()`. |

A token refused as not valid yet (`10005`) is presented again after 3 seconds instead of asking for a new one.

**Returns** a `VobizAccessTokenSession`:

| Member | Description |
| - | - |
| `DateTime? nextRefreshAt` | When the next renewal is scheduled. |
| `Stream<VobizException> failures` | Emits when the session gives up. |
| `Future<void> refresh()` | Asks for a new token now. |
| `Future<void> dispose()` | Stops renewing. It does not sign out: call `client.disconnect()` too. |

**Throws** `VobizAccessTokenException` when the provider fails or returns something that isn't a Vobiz token.

`VobizBackendAccessTokenProvider` is a ready-made provider. It sends `POST <url>` with `{"reason": "sign_in" | "expiring" | "rejected" | "refresh"}` and your headers, and reads the `token` field of the JSON reply:

```json theme={null}
{ "token": "YOUR_ACCESS_TOKEN" }
```

```dart theme={null}
Future<VobizAccessTokenSession> signInWithTokens(VobizClient client) async {
  final provider = VobizBackendAccessTokenProvider(
    url: Uri.parse('https://api.example.com/voice/token'),
    headers: () async => {'Authorization': 'Bearer YOUR_APP_SESSION_TOKEN'},
  );
  final session = await client.connectWithAccessTokenProvider(provider.call);
  session.failures.listen((e) => debugPrint('Token renewal stopped: ${e.message}'));
  return session;
}
```

### Renew a token

```dart Signature theme={null}
Future<void> updateAccessToken(String accessToken)
```

Presents a new token for the same user without dropping the connection or a call. Use it if you renew tokens yourself instead of using a provider. It also recovers a client whose token was refused.

**Throws** `StateError` unless the client signed in with an access token, and `ArgumentError` when the token is for another user (a different `sub` or `iss`). To switch users, call `connectWithAccessToken` again.

### Inspect the token

`client.accessToken` returns the current token as a `VobizAccessToken`, and `client.accessTokenTimeLeft` returns how long the registrar will accept it (from the registrar's own clock).

| `VobizAccessToken` member | Description |
| - | - |
| `String token` | The raw JWT. |
| `String accountId` | The `iss` claim. |
| `String? subject` | The `sub` claim. |
| `String? appId` | The `app` claim. |
| `DateTime notBefore` / `DateTime expiresAt` | The validity window. |
| `bool? incomingAllowed` / `bool? outgoingAllowed` | The `per.voice` grants. |
| `String sipUsername` | The identity the client registers as. |
| `bool canCallOut` / `bool canReceiveCalls` | `true` when the matching grant is `true`. |
| `bool isExpired([DateTime? now])` | Whether `exp` has passed. |
| `Duration timeLeft([DateTime? now])` | Time until `exp` by the device clock. |
| `VobizAccessToken.parse(String token)` | Decodes a token without verifying its signature. Throws `VobizAccessTokenException` (10001) if it isn't a Vobiz token. |

## Demo mode: Zero-Config

> [!WARNING]
>
> Zero-Config sends your account **Auth ID and Auth Token** from the device to a webhook server. The Auth Token is your account's full API key. Use it only for demos and internal testing, never in a shipped app.

```dart Signature theme={null}
Future<ZeroConfigSession> connectWithAuthToken({
  required String authId,
  required String authToken,
})
```

It works like the [WebRTC Playground](https://www.vobiz.ai/docs/integrations/webrtc-application-setup.md): the webhook server at `SdkConfig.backendUrl` finds or creates an application named "Vobiz WebRTC Playground" and its endpoint on your account, gives the endpoint a new password, and returns its credentials. The client then registers as that endpoint. Because the password changes on every sign-in, two devices signed in to the same account sign each other out.

It requires `SdkConfig(unsafeDemoZeroConfig: true)` and **throws** `VobizDemoModeRequiredException` otherwise, `ArgumentError` when a value is empty, and `VobizException` (`setup_failed`) when the server refuses the credentials or can't be reached.

**Returns** a `ZeroConfigSession` with `sipUsername`, `sipPassword`, `applicationId`, `message`, and `reusedExisting`.

Zero-Config is also the only mode that can [transfer calls](https://www.vobiz.ai/docs/integrations/flutter-sdk/in-call-controls.md#transfer-a-call-demo-mode) and read the [recordings list](https://www.vobiz.ai/docs/integrations/flutter-sdk/in-call-controls.md#recordings-demo-mode).

## Watch the connection

```dart theme={null}
void watchConnection(VobizClient client) {
  client.connectionEvents.listen((event) {
    switch (event.registrationState) {
      case RegistrationState.registered:
        debugPrint('Registered as ${client.sipUsername}');
      case RegistrationState.failed:
        debugPrint('Registration failed: ${event.message}');
      case RegistrationState.registering:
      case RegistrationState.unregistered:
        break;
    }
  });
  client.errorEvents.listen((error) => debugPrint('${error.code}: ${error.message}'));
}
```

| Getter | Type | Description |
| - | - | - |
| `isConnected` | `bool` | `true` when connected and registered. |
| `connectionState` | `ConnectionStateStatus` | `disconnected`, `connecting`, `connected`, `reconnecting`, or `failed`. |
| `registrationState` | `RegistrationState` | `unregistered`, `registering`, `registered`, or `failed`. |
| `authMode` | `VobizAuthMode` | `none`, `sipDirect`, `accessToken`, or `zeroConfig`. |
| `sipUsername` | `String?` | The identity the client registered as. |

See [Events and states](https://www.vobiz.ai/docs/integrations/flutter-sdk/events.md) for every event.

## Sign out and clean up

```dart Signature theme={null}
Future<void> disconnect({bool unregister = true})
Future<void> dispose()
void reconnect()
```

| Method | Description |
| - | - |
| `disconnect()` | Signs out. A call in progress is ended first: a ringing call is declined with 480 and an answered call gets a BYE. Then the client unregisters (`Expires: 0`, waiting at most about 2 seconds), closes the connection, and forgets every credential and token. |
| `disconnect(unregister: false)` | Closes the connection without unregistering, as when Android kills the app. Vobiz keeps the registration until it expires, so calls take the [push-to-wake](https://www.vobiz.ai/docs/integrations/flutter-sdk/push-notifications.md) path. Use it to test push; a normal sign-out leaves `unregister` at `true`. |
| `dispose()` | Signs out, then closes every stream. Call it once, when the client is no longer needed. |
| `reconnect()` | Reconnects and re-registers now, resetting the retry backoff. Use it from a retry button after `reconnect_failed`, or when a push arrives. Does nothing while signed out. |

```dart theme={null}
Future<void> signOut(VobizClient client, VobizAccessTokenSession? session) async {
  await session?.dispose();
  await client.disconnect();
}
```

## Next steps

* [Make and receive calls](https://www.vobiz.ai/docs/integrations/flutter-sdk/calls.md)
* [Events and states](https://www.vobiz.ai/docs/integrations/flutter-sdk/events.md)
* [Errors and troubleshooting](https://www.vobiz.ai/docs/integrations/flutter-sdk/errors.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.