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

# Auth and 2FA service — SportsX C# SDK

> Complete reference for STXLoginService, STXTokenService, and the session background worker — parameters, response fields, exceptions, and C# usage examples.

Authentication in the SportsX C# SDK is split across two service classes that serve different use cases. `STXLoginService` wraps the entire login flow in a single method and is the right choice for most integrations. `STXTokenService` exposes each step individually — login, 2FA confirmation, and token refresh — giving you fine-grained control when you need to build a multi-step UI or handle the 2FA challenge separately. `STXSessionBackgroundService` runs automatically when you request session keep-alive, so you don't need to interact with it directly. For task-oriented examples, see the [Authentication guide](/sdks/csharp/authentication).

***

## LoginAsync (STXLoginService)

Authenticates the user with email and password. Optionally checks for pending terms-and-conditions acceptance and starts automatic token refresh.

**Return type:** `Task<STXUserDataCollection>`

### Parameters

| Name                      | Type     | Required | Description                                                                                                                                                                                                        |
| ------------------------- | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `email`                   | `string` | Yes      | The user's registered email address.                                                                                                                                                                               |
| `password`                | `string` | Yes      | The user's password.                                                                                                                                                                                               |
| `checkTermsAndConditions` | `bool`   | No       | When `true`, the SDK checks for pending T\&C acceptance and sets `PromptTncAcceptance` on the result. Defaults to `false`.                                                                                         |
| `keepSessionAlive`        | `bool`   | No       | When `true`, starts `STXSessionBackgroundService`, which refreshes the JWT and re-logs in automatically before the session expires. Requires the SDK to be registered under a hosted `IHost`. Defaults to `false`. |
| `deviceId`                | `string` | No       | A client-provided device identifier. Defaults to `STXDefaultSettings.DeviceId`.                                                                                                                                    |

### Example

```csharp theme={null}
STXUserDataCollection session = await _loginService.LoginAsync(
    email: "user@example.com",
    password: "s3cr3t",
    checkTermsAndConditions: true,
    keepSessionAlive: true);

if (session.PromptTwoFactor)
{
    // Prompt the user for their OTP and call Confirm2FAAsync
    Console.WriteLine("2FA required — enter your code.");
}

if (session.PromptTncAcceptance)
{
    // Surface the T&C acceptance UI
    Console.WriteLine("New terms must be accepted before trading.");
}
```

### Exceptions

| Exception                      | When it is thrown                                        |
| ------------------------------ | -------------------------------------------------------- |
| `STXWrongCredentialsException` | The email or password is incorrect.                      |
| `STXGeoComplyException`        | The GeoComply geo-check failed for the current location. |

***

## LoginAsync (STXTokenService)

The low-level login method that `STXLoginService.LoginAsync` delegates to internally. Use this directly when you need to separate the login step from 2FA confirmation in your own flow.

**Return type:** `Task<STXUserDataCollection>`

### Parameters

| Name               | Type     | Required | Description                                                                     |
| ------------------ | -------- | -------- | ------------------------------------------------------------------------------- |
| `email`            | `string` | Yes      | The user's registered email address.                                            |
| `password`         | `string` | Yes      | The user's password.                                                            |
| `keepSessionAlive` | `bool`   | Yes      | Whether to start the background session-renewal service.                        |
| `deviceId`         | `string` | No       | A client-provided device identifier. Defaults to `STXDefaultSettings.DeviceId`. |

### Example

```csharp theme={null}
// Step 1 — authenticate
STXUserDataCollection initial = await _tokenService.LoginAsync(
    email: "user@example.com",
    password: "s3cr3t",
    keepSessionAlive: false);

if (initial.PromptTwoFactor)
{
    // Step 2 — complete 2FA (see Confirm2FAAsync below)
}
```

***

## Confirm2FAAsync

Completes a two-factor authentication challenge. Call this after `LoginAsync` returns a response with `PromptTwoFactor: true`. You need the OTP code from the user, plus the `SessionId` and `Email` from the initial login response.

**Return type:** `Task<STXUserDataCollection>`

### Parameters

| Name        | Type     | Required | Description                                                                  |
| ----------- | -------- | -------- | ---------------------------------------------------------------------------- |
| `code`      | `string` | Yes      | The one-time password (OTP) provided by the user's authenticator app or SMS. |
| `sessionId` | `string` | Yes      | The `SessionId` returned by the initial `LoginAsync` call.                   |
| `email`     | `string` | Yes      | The email address used for the initial login.                                |

### Example

```csharp theme={null}
// Collect the OTP from the user (e.g. from a form input)
string otp = GetOtpFromUser();

STXUserDataCollection session = await _tokenService.Confirm2FAAsync(
    code: otp,
    sessionId: initial.SessionId,
    email: "user@example.com");

// session.Token is now valid for API calls
Console.WriteLine($"Authenticated. User ID: {session.UserId}");
```

***

## RefreshTokenAsync

Exchanges the stored refresh token for a new JWT. Call this when you receive `STXTokenExpiredException` on an API call and want to retry without a full re-login.

**Return type:** `Task<STXUserDataCollection>`

### Parameters

This method takes no parameters. The SDK reads the refresh token from its internal `STXUserStorage`.

### Example

```csharp theme={null}
try
{
    var data = await _marketService.GetMarketInfosAsync();
}
catch (STXTokenExpiredException)
{
    await _tokenService.RefreshTokenAsync();
    // Retry the original call
    var data = await _marketService.GetMarketInfosAsync();
}
```

### Exceptions

| Exception                    | When it is thrown                                                                  |
| ---------------------------- | ---------------------------------------------------------------------------------- |
| `STXSessionExpiredException` | Both the JWT and the refresh token have expired. You must perform a full re-login. |

***

## STXUserDataCollection

`LoginAsync`, `Confirm2FAAsync`, and `RefreshTokenAsync` all return this model.

| Field                 | Description                                                                        |
| --------------------- | ---------------------------------------------------------------------------------- |
| `Token`               | JWT bearer token — include as `Authorization: Bearer <token>` for GraphQL requests |
| `RefreshToken`        | Opaque token used by `RefreshTokenAsync` to obtain a new JWT                       |
| `UserId`              | Numeric user identifier — used as `{user_id}` in WebSocket channel topic strings   |
| `UserUid`             | UUID-format user identifier                                                        |
| `SessionId`           | Required as input to `Confirm2FAAsync` when 2FA is enabled                         |
| `CurrentLoginAt`      | UTC timestamp of the current login                                                 |
| `PromptTncAcceptance` | `true` when the user must accept a new version of the terms and conditions         |
| `PromptTwoFactor`     | `true` when a 2FA challenge is pending and `Confirm2FAAsync` must be called        |

***

## STXSessionBackgroundService

`STXSessionBackgroundService` is a hosted background service that you never call directly. It activates automatically when you pass `keepSessionAlive: true` to either `LoginAsync` overload.

**What it does:**

* Every approximately 15 minutes, it checks whether the JWT is within the expiry window. If so, it calls `RefreshTokenAsync` to extend the session.
* If the refresh token itself is nearing expiry, it performs a full re-login using the credentials cached in `STXUserStorage`.

<Note>
  `keepSessionAlive: true` requires the SDK to be registered with a .NET hosted service container (i.e., under an `IHost` that runs background services). In console applications or worker services this works out of the box; in ASP.NET Core, ensure `AddHostedService` is not suppressed.
</Note>
