# Schwab OAuth2 Setup Guide

## Overview

The Schwab Trader API uses OAuth 2.0 authorization code flow for authentication. This n8n node leverages n8n's built-in OAuth2 support, which handles the token exchange and refresh automatically.

## Prerequisites

1. A Schwab brokerage account
2. Access to Schwab Developer Portal
3. n8n instance (self-hosted or cloud)

## Step-by-Step Setup

### 1. Register Your Application at Schwab

1. Go to [Schwab Developer Portal](https://developer.schwab.com/)
2. Sign in with your Schwab account
3. Navigate to "My Apps" or "Applications"
4. Click "Create New App" or "Register Application"
5. Fill in the application details:
   - **App Name**: Choose a name (e.g., "n8n Integration")
   - **Description**: Brief description of your use case
   - **Redirect URI**: Get this from n8n (see next section)
   - **Scopes**: Select the permissions you need:
     - `readonly` - Read account and market data
     - `trade` - Place and manage trades
     - You can select both by using `readonly trade`

6. Submit the application
7. **Save your credentials**:
   - ✅ Client ID (App Key)
   - ✅ Client Secret (App Secret)

### 2. Get OAuth Redirect URL from n8n

**Important**: n8n handles the OAuth flow automatically. You need to get the redirect URL from n8n first.

#### For n8n Cloud:
The redirect URL will be: `https://your-instance.app.n8n.cloud/rest/oauth2-credential/callback`

#### For Self-Hosted n8n:
The redirect URL will be: `https://your-domain.com/rest/oauth2-credential/callback`

To get the exact URL:
1. In n8n, go to **Credentials** → **New Credential**
2. Search for "Schwab OAuth2 API"
3. The OAuth Redirect URL will be displayed at the top
4. **Copy this URL** - you'll need it for the Schwab app registration

### 3. Configure Credentials in n8n

1. **In n8n**, go to **Credentials** → **Create New**
2. Search for "Schwab OAuth2 API"
3. Fill in the fields:
   - **Client ID**: Your Schwab app's Client ID
   - **Client Secret**: Your Schwab app's Client Secret
   - **Redirect URI**: This should auto-fill (the same URL from step 2)
   
4. Click **"Connect my account"** or **"OAuth2 Connect"** button
   
5. **You'll be redirected to Schwab**:
   - Login with your Schwab credentials
   - Review and authorize the permissions
   - You'll be automatically redirected back to n8n

6. **In n8n**, you should see a success message
7. Click **"Save"** to save the credential

That's it! n8n now has a valid OAuth2 token and will automatically refresh it when needed.

## Using the Credentials

Once saved, you can use the Schwab OAuth2 API credential in your workflows:

1. Add a **Schwab** node to your workflow
2. In the node settings, select your saved credential
3. Choose the operation you want to perform
4. The node will automatically use the OAuth2 token for authentication

## Token Management

### Automatic Token Refresh

n8n automatically handles token refresh! When the access token expires, n8n will:
1. Use the refresh token to get a new access token
2. Update the stored credentials
3. Retry the failed request

You don't need to do anything manually.

### Token Expiration

- **Access tokens** expire after 30 minutes
- **Refresh tokens** are valid for 90 days
- n8n will automatically refresh tokens as needed

### Re-authorization

If your refresh token expires (after 90 days of inactivity), you'll need to:
1. Edit the credential in n8n
2. Click "Reconnect" or "OAuth2 Connect" again
3. Authorize with Schwab again

## Scopes

The Schwab API supports the following scopes:

| Scope | Description | Use Case |
|-------|-------------|----------|
| `readonly` | Read-only access to account data | Portfolio tracking, market data |
| `trade` | Trading permissions | Place orders, manage positions |
| `readonly trade` | Both scopes | Full trading automation |

**Default**: The credential uses `readonly` by default. To add trading capabilities, you may need to update the scope in the credential configuration.

## Troubleshooting

### Error: "OAuth2 credential callback failed"
- Verify the redirect URI in Schwab app matches exactly the one from n8n
- Check that your Schwab app is approved/active
- Ensure your n8n instance is accessible from the internet (for cloud OAuth callback)

### Error: "Invalid Client"
- Double-check your Client ID and Client Secret
- Verify your app status in Schwab Developer Portal

### Error: "Insufficient Scope"
- Your app doesn't have the necessary permissions
- Update scopes in the Schwab Developer Portal
- Re-connect the credential in n8n

### Error: "Token expired" (persists)
- The refresh token may have expired
- Reconnect the credential in n8n

### Self-Hosted n8n: OAuth Callback Issues
If you're self-hosting n8n:
- Your n8n instance **must** be accessible via HTTPS
- The domain must be reachable from the internet (Schwab needs to call back)
- Update `N8N_HOST` environment variable to your public URL
- For local development, consider using ngrok or similar tunneling service

## Security Best Practices

1. **Never share credentials**:
   - Don't commit OAuth tokens to version control
   - Use n8n's credential management (encrypted storage)
   - Don't log or expose tokens in workflows

2. **Use HTTPS**:
   - Always use HTTPS for your n8n instance in production
   - Schwab requires HTTPS for production OAuth callbacks

3. **Limit scope**:
   - Only request the permissions you need
   - Use `readonly` for portfolio tracking
   - Add `trade` only when placing orders

4. **Monitor access**:
   - Regularly review active OAuth connections in Schwab Developer Portal
   - Revoke unused applications
   - Rotate credentials periodically

5. **Environment separation**:
   - Use different Schwab apps for development/production
   - Don't reuse production credentials in testing

## Comparison with Manual OAuth Flow

### ❌ Old Way (Manual - v0.1.0):
- Had to manually get authorization code
- Had to manually exchange for access token
- Had to manually implement token refresh
- Tokens could expire without warning

### ✅ New Way (n8n Native OAuth2 - v0.2.0+):
- Click "Connect" button in n8n
- n8n handles entire OAuth flow
- Automatic token refresh
- No manual intervention needed
- Tokens always fresh

## Additional Resources

- [Schwab Developer Documentation](https://developer.schwab.com/products/trader-api--individual)
- [OAuth 2.0 Specification](https://oauth.net/2/)
- [n8n OAuth2 Documentation](https://docs.n8n.io/integrations/builtin/credentials/)
- [Schwab API Support](https://developer.schwab.com/support)

## Getting Help

If you encounter issues:
1. Check the [Schwab Developer Forums](https://developer.schwab.com/forum)
2. Open an issue on the GitHub repository
3. Ask in the [n8n Community](https://community.n8n.io/)

---

**Note**: With v0.2.0+, the OAuth setup is now fully automated through n8n's built-in OAuth2 support. Just click "Connect" and authorize - n8n handles everything else!
