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

# API Authentication

> Securely authenticate users using the OAuth 2.0 Authorization Code Grant.

Our API uses the industry-standard OAuth 2.0 protocol for authentication.

If your application needs to access data or take actions on behalf of an iON end-user (e.g., an integration like IFTTT), you must use the **Authorization Code Grant**.

### Step 1: Getting Your API Credentials

Before you can authenticate, you must register your application to receive a unique `Client ID` and `Client Secret`.

1. Go to the [iON Developer Portal](https://portal.ionelectricity.com).
2. Log in with your iON account.
3. Click **Create New Application** and enter your `redirect_uri` (callback URL).
4. Copy your `Client ID` and `Client Secret`. Store your secret securely in your backend.

***

### Step 2: Redirect the User to the Authorize Endpoint

Construct a URL and redirect the user's browser to it. This will show them the iON login screen.

`GET https://auth.ionelectricity.com/oauth2/authorize`

**Query Parameters:**

* `response_type`: `code`
* `client_id`: `YOUR_CLIENT_ID`
* `redirect_uri`: The URL in your application where the user should be sent after logging in.
* `scope`: `openid profile email`

***

### Step 3: Exchange the Code for an ID Token

After the user logs in, they are redirected back to your `redirect_uri` with a temporary `code` in the URL parameters. Your backend server must exchange this code for an `id_token`.

**Important:** You must use Basic Authentication by Base64-encoding your `ClientID:ClientSecret`.

```javascript Node.js theme={null}
const basicAuth = Buffer.from(`${clientId}:${clientSecret}`).toString("base64");

const params = new URLSearchParams({
  grant_type: "authorization_code",
  client_id: clientId,
  code: "THE_CODE_FROM_STEP_2",
  redirect_uri: "YOUR_CALLBACK_URL",
});

const response = await fetch("https://auth.ionelectricity.com/oauth2/token", {
  method: "POST",
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
    Authorization: `Basic ${basicAuth}`,
  },
  body: params.toString(),
});

const tokens = await response.json();
console.log(tokens.id_token); // Your Bearer Token!
```

You can now use the `id_token` as a Bearer token in the `Authorization` header to read data from the iON API.
