> ## 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 in Ruby XDK

> Configure Bearer Token, OAuth 2.0 PKCE, and OAuth 1.0a authentication with the Ruby XDK.

`Xdk::Client` supports all three X API authentication schemes and automatically chooses the appropriate header for each endpoint (preferring user context on write endpoints and Bearer Token on read endpoints when multiple credentials are supplied).

## Bearer Token (App-Only)

```ruby theme={null}
client = Xdk::Client.new(bearer_token: ENV.fetch("X_BEARER_TOKEN"))
```

## OAuth 2.0 User Context (PKCE)

### With an existing user access token

```ruby theme={null}
client = Xdk::Client.new(access_token: ENV.fetch("X_ACCESS_TOKEN"))
```

### Full PKCE authorization & refresh flow

```ruby theme={null}
client = Xdk::Client.new(
  client_id: ENV.fetch("X_CLIENT_ID"),
  client_secret: ENV["X_CLIENT_SECRET"], # omit for public clients
  redirect_uri: "http://localhost:8080/callback",
  scope: %w[tweet.read tweet.write users.read dm.read dm.write offline.access]
)

# 1. Redirect user to the authorization URL
auth_url = client.get_authorization_url(state: "csrf-state")

# 2. Exchange the authorization code returned to your callback
token = client.exchange_code(params[:code])

# 3. Refresh when expired (the client also refreshes automatically before requests)
token = client.refresh_token if client.token_expired?
```

## OAuth 1.0a (HMAC-SHA1)

```ruby theme={null}
oauth1 = Xdk::OAuth1.new(
  api_key: ENV.fetch("X_API_KEY"),
  api_secret: ENV.fetch("X_API_SECRET"),
  access_token: ENV.fetch("X_ACCESS_TOKEN"),
  access_token_secret: ENV.fetch("X_ACCESS_TOKEN_SECRET")
)

client = Xdk::Client.new(auth: oauth1)
```

For 3-legged OAuth 1.0a login:

```ruby theme={null}
oauth1 = Xdk::OAuth1.new(
  api_key: ENV.fetch("X_API_KEY"),
  api_secret: ENV.fetch("X_API_SECRET"),
  callback: "http://localhost:8080/callback"
)

oauth1.get_request_token
redirect_url = oauth1.get_authorization_url
# After callback with oauth_verifier:
oauth1.get_access_token(verifier)
```
