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

# Authentication

> Configure Bearer Token, OAuth 2.0 PKCE, or OAuth 1.0a in the C# / .NET XDK.

`XClient` supports Bearer Token (app-only), OAuth 2.0 with PKCE (user context), and OAuth 1.0a (user context) via `XClientOptions`. Get your credentials from the [X Developer Console](https://console.x.com).

## Bearer Token

```csharp theme={null}
using System;
using Xdk;

using var client = new XClient(new XClientOptions
{
    BearerToken = Environment.GetEnvironmentVariable("X_BEARER_TOKEN"),
});

var user = await client.Users.GetByUsernameAsync("XDevelopers");
```

## OAuth 2.0 with PKCE

If you already have a user access token:

```csharp theme={null}
using var client = new XClient(new XClientOptions
{
    AccessToken = Environment.GetEnvironmentVariable("X_ACCESS_TOKEN"),
});

var me = await client.Users.GetMeAsync();
```

To run the PKCE authorization flow and refresh tokens with `OAuth2Pkce`:

```csharp theme={null}
using System;
using Xdk;
using Xdk.Auth;
using Xdk.Models;

var oauth2 = new OAuth2Pkce(
    clientId: Environment.GetEnvironmentVariable("X_CLIENT_ID")!,
    redirectUri: "http://localhost:8080/callback",
    clientSecret: Environment.GetEnvironmentVariable("X_CLIENT_SECRET"), // null for public clients
    scopes: new[] { "tweet.read", "tweet.write", "users.read", "offline.access" }
);

// 1. Direct the user to authorize your app
string authorizationUrl = oauth2.GetAuthorizationUrl("random-csrf-state");

// 2. Exchange the callback `code` parameter for tokens
OAuth2Token token = await oauth2.ExchangeCodeAsync(callbackCode);

// 3. Create XClient with the OAuth2Pkce instance
using var client = new XClient(new XClientOptions
{
    OAuth2 = oauth2,
});

var created = await client.Posts.CreateAsync(new CreatePostsRequest
{
    Text = "Hello from C# XDK!",
});

// Refresh tokens when needed (requires offline.access scope)
await client.RefreshTokenAsync();
```

## OAuth 1.0a

```csharp theme={null}
using System;
using Xdk;
using Xdk.Auth;

var oauth1 = new OAuth1(
    apiKey: Environment.GetEnvironmentVariable("X_API_KEY")!,
    apiSecret: Environment.GetEnvironmentVariable("X_API_SECRET")!,
    callback: "oob",
    accessToken: Environment.GetEnvironmentVariable("X_ACCESS_TOKEN"),
    accessTokenSecret: Environment.GetEnvironmentVariable("X_ACCESS_TOKEN_SECRET")
);

using var client = new XClient(new XClientOptions
{
    OAuth1 = oauth1,
});

var me = await client.Users.GetMeAsync();
```

See the [C# samples repo](https://github.com/xdevplatform/samples/tree/main/csharp) for more examples.
