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

# Authentication

> Set up API authentication for C#/.NET SDK

## Getting Your API Key

1. Visit [Legnext.ai Dashboard](https://legnext.ai/dashboard)
2. Navigate to API Keys section
3. Generate a new API key
4. Copy and store securely

## Authentication Methods

### Method 1: Environment Variables (Recommended)

Set your API key as an environment variable:

```bash theme={null}
export LEGNEXT_API_KEY="your-api-key-here"
```

Then use it in your C# code:

```csharp theme={null}
using System;
using Microsoft.Extensions.DependencyInjection;
using Legnext.SDK.Api;
using Legnext.SDK.Client;
using Legnext.SDK.Extensions;

string apiKey = Environment.GetEnvironmentVariable("LEGNEXT_API_KEY");

var services = new ServiceCollection();
services.AddApi(config =>
{
    config.AddApiHttpClients(client =>
    {
        client.BaseAddress = new Uri("https://api.legnext.ai");
    });
});

var provider = services.BuildServiceProvider();
var imageApi = provider.GetRequiredService<IImageApi>();

// Use imageApi with apiKey in method calls
var response = await imageApi.ApiV1DiffusionPostAsync(
    new Option<string>(apiKey),
    request
);
```

### Method 2: appsettings.json Configuration

For ASP.NET Core applications:

**appsettings.json:**

```json theme={null}
{
  "Legnext": {
    "ApiKey": "your-api-key-here",
    "BaseUrl": "https://api.legnext.ai"
  }
}
```

**Usage:**

```csharp theme={null}
string apiKey = Configuration["Legnext:ApiKey"];
string baseUrl = Configuration["Legnext:BaseUrl"];
```

### Method 3: User Secrets (Development)

For development environments:

```bash theme={null}
dotnet user-secrets init
dotnet user-secrets set "Legnext:ApiKey" "your-api-key-here"
```

Then access in code:

```csharp theme={null}
string apiKey = Configuration["Legnext:ApiKey"];
```

***

## Complete Setup Example

```csharp theme={null}
using System;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Legnext.SDK.Api;
using Legnext.SDK.Client;
using Legnext.SDK.Extensions;

public class LegnextService
{
    private readonly IServiceProvider _serviceProvider;
    private readonly string _apiKey;

    public LegnextService(string apiKey)
    {
        _apiKey = apiKey;

        var services = new ServiceCollection();
        services.AddApi(config =>
        {
            config.AddApiHttpClients(client =>
            {
                client.BaseAddress = new Uri("https://api.legnext.ai");
                client.Timeout = TimeSpan.FromMinutes(5);
            });
        });

        _serviceProvider = services.BuildServiceProvider();
    }

    public async Task<string> GenerateImageAsync(string prompt)
    {
        var imageApi = _serviceProvider.GetRequiredService<IImageApi>();

        var request = new Dictionary<string, object>
        {
            { "text", prompt }
        };

        var response = await imageApi.ApiV1DiffusionPostAsync(
            new Option<string>(_apiKey),
            request
        );

        if (response.IsOk)
        {
            var jsonDoc = JsonDocument.Parse(response.RawContent);
            if (jsonDoc.RootElement.TryGetProperty("job_id", out var jobId))
            {
                return jobId.GetString();
            }
        }

        throw new Exception("Failed to generate image");
    }
}
```

***

## Security Best Practices

1. **Never hardcode API keys**
2. **Use different keys for different environments**
3. **Never commit secrets to version control**
4. **Rotate keys regularly**
5. **Use secure storage in production** (Azure Key Vault, AWS Secrets Manager)
6. **Enable HTTPS only**

***

## Testing Authentication

```csharp theme={null}
using System;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Legnext.SDK.Api;
using Legnext.SDK.Client;
using Legnext.SDK.Extensions;

string apiKey = Environment.GetEnvironmentVariable("LEGNEXT_API_KEY");

var services = new ServiceCollection();
services.AddApi(config =>
{
    config.AddApiHttpClients(client =>
    {
        client.BaseAddress = new Uri("https://api.legnext.ai");
    });
});

var provider = services.BuildServiceProvider();
var accountApi = provider.GetRequiredService<IAccountManagementApi>();

try
{
    var response = await accountApi.ApiAccountBalanceGetAsync(
        new Option<string>(apiKey)
    );

    if (response.IsOk)
    {
        Console.WriteLine("✅ Authentication successful!");

        var jsonDoc = JsonDocument.Parse(response.RawContent);
        if (jsonDoc.RootElement.TryGetProperty("data", out var data))
        {
            if (data.TryGetProperty("balance_usd", out var balance))
            {
                Console.WriteLine($"Balance: ${balance.GetDecimal()} USD");
            }
        }
    }
}
catch (Exception e)
{
    Console.WriteLine("❌ Authentication failed");
    Console.WriteLine($"Error: {e.Message}");
}
```

***

## Next Steps

* [Image Generation](/sdk/csharp/image-generation)
* [Video Generation](/sdk/csharp/video-generation)
* [Task Management](/sdk/csharp/task-management)
* [Quick Start](/sdk/csharp/quickstart)
