> ## 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 Java XDK.

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

## Bearer Token

```java theme={null}
import com.x.xdk.XClient;

XClient client = XClient.builder()
    .bearerToken(System.getenv("X_BEARER_TOKEN"))
    .build();

var user = client.users().getByUsername("XDevelopers");
```

## OAuth 2.0 with PKCE

If you already have a user access token:

```java theme={null}
XClient client = XClient.builder()
    .accessToken(System.getenv("X_ACCESS_TOKEN"))
    .build();

var me = client.users().getMe();
```

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

```java theme={null}
import com.x.xdk.Schemas;
import com.x.xdk.XClient;
import com.x.xdk.auth.OAuth2Pkce;
import com.x.xdk.auth.OAuth2Token;
import java.util.List;

OAuth2Pkce oauth2 = new OAuth2Pkce(
    System.getenv("X_CLIENT_ID"),
    System.getenv("X_CLIENT_SECRET"), // null for public clients
    "http://localhost:8080/callback",
    List.of("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 = oauth2.exchangeCode(callbackCode);

// 3. Build XClient with the OAuth2Pkce instance
XClient client = XClient.builder()
    .oauth2(oauth2)
    .build();

Schemas.CreatePostsResponse created = client.posts().create(
    new Schemas.CreatePostsRequest().text("Hello from Java XDK!")
);

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

## OAuth 1.0a

```java theme={null}
import com.x.xdk.Schemas;
import com.x.xdk.XClient;
import com.x.xdk.auth.OAuth1;

OAuth1 oauth1 = new OAuth1(
    System.getenv("X_API_KEY"),
    System.getenv("X_API_SECRET"),
    "oob",
    System.getenv("X_ACCESS_TOKEN"),
    System.getenv("X_ACCESS_TOKEN_SECRET")
);

XClient client = XClient.builder()
    .oauth1(oauth1)
    .build();

Schemas.GetUsersMeResponse me = client.users().getMe();
```

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