# Authentication

### Authenticating with OAuth 2.0 using the VARIO App Framework

When you build your own Node.js backend (not using the demo app repository), you can still use the **VARIO App Framework backend package** to handle authentication for you.

At a high level:

* Your app **stores** the VARIO Cloud credentials and refresh tokens.
* The **framework backend** handles:
  * OAuth 2.0 *refresh token* grant
  * obtaining and caching access tokens
  * adding `Authorization: Bearer <access_token>` to all VARIO API calls ([GitHub](https://github.com/vario-software/vario-app-framework?utm_source=chatgpt.com))

You never have to call the token endpoint manually.

***

#### 1. What you need before you start

To authenticate via the framework backend you need:

1. **App credentials (AppClient)** from the VARIO-Cloud Admin Center\
   (see *“Creating a new App and getting API credentials”*):
   * `appIdentifier`
   * `clientId`
   * `clientSecret`
2. **One refresh token per VARIO-Cloud installation**
   * Obtained once during the installation/authorization flow of your app (e.g. on your `pcInstallationUrl`).
   * Stored securely in your own database or configuration.
3. **Base URLs for your environment**
   * VARIO Cloud API base URL (business API)
   * OAuth 2.0 token endpoint URL

The framework will use `clientId`, `clientSecret`, and the installation-specific `refreshToken` to obtain access tokens via `grant_type=refresh_token`.

***

#### 2. Install the framework backend

In your Node.js backend project:

```
npm install @vario-software/vario-app-framework-backend
```

The backend package is responsible for **API communication and authentication**. ([libraries.io](https://libraries.io/npm/%40vario-software%2Fvario-app-framework-backend?utm_source=chatgpt.com))

> The frontend package (`@vario-software/vario-app-framework-frontend`) is optional here and only relevant for styling/JS helpers in your UI.

***

#### 3. Provide configuration: app client + installations

Your app needs a way to provide two types of data to the framework:

1. **Static app client config** (same for all installations):

   ```
   {
     "appIdentifier": "your-app-identifier",
     "clientId": "your-client-id",
     "clientSecret": "your-client-secret",
     "appJWK": "JWK_TOKEN"
   }
   ```

   You can use an `app-client.json` file (similar to the demo app) or environment variables. The demo app reads this file at startup and passes the values into the framework.
2. **Installation-specific refresh tokens**

   For each customer/tenant installation:

   * You receive a **refresh token** during the app installation/authorization flow.
   * You store it in a database table like `app_installations`:
     * `installation_id`
     * `refresh_token`
     * maybe also tenant-specific URLs / metadata.

***

#### 4. Initialize the framework backend

In your backend, create a module responsible for wiring **your configuration** into the framework.

Example structure:

```
const frameworkApp = /* createBackendApp */({
  appIdentifier: appClient.appIdentifier,
  clientId: appClient.clientId,
  clientSecret: appClient.clientSecret,
  appJWK: appClient.appJWK
  // optional: base URLs, logging, etc.
});

// Helper for your routes: get an authenticated client for a given installation
export async function getVarioClient(installationId: string) {
  const installation = await loadInstallation(installationId);

  // Ask the framework for a client that uses the refresh token
  const client = await frameworkApp.getApiClient({
    installationId,
    refreshToken: installation.refreshToken,
    // Called when the framework receives a rotated refresh token
    onRefreshTokenUpdated: async (newRefreshToken: string) => {
      installation.refreshToken = newRefreshToken;
      await saveInstallation(installation);
    },
  });

  return client; // used to call VARIO APIs
}
```

***

#### 5. Use the framework client in your own routes

Once you have a helper like `getVarioClient(installationId)`, you can use it inside your Express (or Fastify, etc.) route handlers.

Example (pseudo-code with Express):

```
// Example: list activities for a given installation
router.get("/api/activities", async (req, res, next) => {
  try {
    // In a real app you derive the installationId from the session, JWT, subdomain, etc.
    const installationId = req.headers["x-installation-id"] as string;

    const client = await getVarioClient(installationId);

    // The framework client hides OAuth:
    // - it ensures access token exists/is valid (using refresh_token if needed)
    // - it calls the VARIO Cloud API with the correct Authorization header
    const activities = await client.get("/crm-activity", {
      // any query parameters, VQL, etc.
    });

    res.json(activities);
  } catch (err) {
    next(err);
  }
});

export default router;
```

From your app’s perspective:

* You **never** manually:
  * call the OAuth token endpoint
  * build `Authorization` headers
  * check expiry times
* You **always**:
  * ask the framework to give you an API client for an installation
  * call `.get()`, `.post()`, etc. on that client

Under the hood the framework:

1. Reads `clientId` / `clientSecret`.
2. Uses the installation’s `refreshToken` to request an access token (`grant_type=refresh_token`).
3. Caches the access token until it expires.
4. Sends the VARIO-Cloud API request with `Authorization: Bearer <access_token>`.
5. If the OAuth server returns a new `refresh_token`, it calls `onRefreshTokenUpdated` so you can persist it.

This is the same pattern that the demo app uses internally, only with its own wiring and file structure.

***

#### 6. Summary

If you build your own app but still use the VARIO App Framework backend:

1. **Create an App** in VARIO Cloud and get `appIdentifier`, `clientId`, `clientSecret`.
2. **Store one refresh token per installation** when your app is installed/authorized.
3. **Install the framework backend**:

   ```
   npm install @vario-software/vario-app-framework-backend
   ```
4. **Initialize the framework** with your app client config.
5. **Create a helper** (similar to the demo app) that:
   * loads the installation’s `refreshToken`
   * asks the framework for an API client
   * persists rotated refresh tokens (if any)
6. **Use that API client** in all your route handlers instead of talking to the VARIO Cloud API directly.

You still use OAuth2 with the **refresh-token grant type**, but the **framework** hides all low-level token handling and keeps your own code focused on business logic.
