Skip to content
| Marketplace
Sign in
Visual Studio Code>Other>Flow Authentication ProviderNew to Visual Studio Code? Get it now.
Flow Authentication Provider

Flow Authentication Provider

CI&T

ciandt.com
|
1 install
| (0) | Free
Authentication Provider for Flow
Installation
Launch VS Code Quick Open (Ctrl+P), paste the following command, and press enter.
Copied to clipboard
More Info

Flow Authentication Provider - Authentication Provider API Sample

This extension demonstrates VS Code's authentication provider API by registering and using a Flow Authentication Provider to authenticate and retrieve tokens from the Flow API.

Features

  • API Key (PAT) flow: prompt for credentials and generate/renew a Personal Access Token (PAT).
  • OAuth flow: perform OAuth 2.0 login, validate and refresh access tokens automatically.
  • Securely store and cache tokens in VS Code SecretStorage.
  • Expose authentication sessions (flowauth.apikey and flowauth.oauth) via the VS Code authentication API.
  • Structured error handling with specific error classes and internal Either utilities.
  • Resilient HTTP calls with a reusable retry strategy.

VS Code API

vscode module

  • authentication.registerAuthenticationProvider
  • authentication.getSession

Running the Example

  1. Open this example in VS Code 1.74+.
  2. Run npm install to install dependencies.
  3. Use cmd/ctrl+shift+b or npm run watch or npm run compile to build the extension.
  4. Press F5 to start debugging the extension.

Usage

  1. Run the Login with Flow command from the Command Palette (Ctrl+Shift+P or Cmd+Shift+P on Mac).
  2. Enter your Flow Client ID, Client Secret, and Tenant Name when prompted.
  3. Upon successful authentication, the token will be securely stored and can be reused in other contexts or extensions.

Example API Call

Once authenticated, you can use the token to make API calls. For example:

const session = await vscode.authentication.getSession('flowauth', [], { createIfNone: false });
if (session) {
    const response = await fetch('https://flow.ciandt.com/some-api-endpoint', {
        method: 'GET',
        headers: {
            Authorization: `Bearer ${session.accessToken}`,
        },
    });
    const data = await response.json();
    console.log(data);
}

Flow Authentication Integration Guide

This guide shows how to consume the Flow Login extension’s credentials (API-Key and OAuth tokens) from your VS Code extension.
It covers installation, configuration, available API, and common usage patterns.

1. Prerequisites

  • VS Code ≥ 1.50
  • Node.js ≥ 12 (your extension host)
  • The Flow Authentication Provider extension installed in VS Code
    • Extension ID: ciandt.flow-authentication-provider

2. Declare a Dependency

In your package.json, add Flow Authentication Provider as a dependency so VS Code will auto-install and activate it before your extension:

{
  "publisher": "your-publisher",
  "name": "your-extension",
  "engines": { "vscode": "^1.50.0" },
  "extensionDependencies": [
    "ciandt.flow-authentication-provider"
  ]
}

3. Triggering Authentication

3.1 API-Key Flow

To start an API-key based login, your extension should execute the login command:

await vscode.commands.executeCommand('flow-authentication-provider.login');

This will prompt the user to enter their Flow Client ID, Client Secret, and Tenant Name, store the credentials securely, and register an API-key authentication session. You can then retrieve the session:

const session = await vscode.authentication.getSession('flowauth.apikey', [], { createIfNone: false });
const apiKeyToken = session?.accessToken;
const clientId = session?.clientId;
const clientSecret = session?.clientSecret;

3.2 OAuth Flow

To initiate the OAuth-based login flow, execute:

await vscode.commands.executeCommand('flow-authentication-provider.oauth');

Alternatively, you can directly request a session (which will trigger login if none exists):

const session = await vscode.authentication.getSession('flowauth.oauth', [], { createIfNone: true });
const oauthToken = session.accessToken;

OAuthInfo Data Structure

When using the OAuth-based login flow, the session object includes additional metadata via the oauthInfo property. The OAuthInfo interface describes this data:

export interface OAuthInfo {
  /** The state parameter used to initiate the OAuth flow */
  flowState: string;
  /** The authorization code returned by the OAuth server for token exchange */
  flowCode: string;
  /** The authorization code received in the redirect callback */
  code: string;
  /** The access token for calling protected Flow APIs */
  token: string;
  /** The refresh token used to renew the access token */
  refreshToken: string;
  /** Additional OAuth code for extended flows */
  oAuthCode: string;
  /** List of tenants associated with the authenticated user */
  tenants: Array<{
    name: string;        // Internal tenant identifier
    displayName: string; // User-friendly tenant name
    isActive: boolean;   // Whether the tenant is currently active
    isPrincipal: boolean;// Whether the tenant is the user's primary tenant
  }>;
  /** Indicates if the user has accepted the terms of service */
  isTermAccepted: boolean;
}

PatAuthInfo Data Structure

When using the API-key flow, to get the Pat-Token, the session object includes additional metadata via the patAuthInfo property. The PatAuthInfo interface describes this data:

export interface PatAuthInfo {
  clientId: string;
  clientSecret: string;
  tenant: string;
  accessToken: string;
  expiresAt: number; // Timestamp in milliseconds
  appsToAccess: string[];
}

You can also use VS Code’s built-in authentication API:

// id: 'flow', scopes: your choice of ['openid','profile',…]
vscode.authentication.getSession('flow', scopes, { createIfNone: boolean });

4. Error Handling

The extension now categorizes failures with specific error classes and uses an internal Either pattern to improve robustness. As a consumer of this extension, you don’t need these classes directly—just handle failures from commands and getSession calls and surface friendly messages.

  • Input prompts in the API-Key flow validate required fields and fail fast with clear messages.
  • REST requests surface HTTP/network issues as actionable messages.
  • Unexpected parsing/runtime issues are reported as unexpected errors.

Example: defensive handling around login and session access

import * as vscode from 'vscode';

export async function safeLoginAndGetPat(): Promise<string | undefined> {
  try {
    await vscode.commands.executeCommand('flow-authentication-provider.login');
    const session = await vscode.authentication.getSession('flowauth.apikey', [], { createIfNone: false });
    if (!session) {
      vscode.window.showWarningMessage('Flow login did not create a session.');
      return undefined;
    }
    return session.accessToken;
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    vscode.window.showErrorMessage(`Flow authentication failed: ${message}`);
    return undefined;
  }
}

Notes for contributors (internal):

  • Error classes live in src/shared/errors.ts (e.g., ValidationError, ApiError, UnexpectedError, etc.).
  • Either helpers live in src/shared/either.ts (Either, left, right, isLeft, isRight).
  • Services/providers should throw specific AppError subclasses or return Either to make error intent explicit.

Retry Strategy

All outbound HTTP requests now use a shared, typed retry utility based on the retry npm package. The helper lives at src/shared/retry.ts and exposes:

  • fetchWithRetry(input, init?, policy?): wraps fetch with exponential backoff and sensible defaults.

Default policy:

  • Retries: 4 attempts, exponential backoff (factor 2), 250–2000ms jittered delays, max 8s total.
  • Retry conditions: network errors, 5xx, 429, and 408. No retries for other 4xx.

Usage example:

import { fetchWithRetry } from '../shared/retry';

const res = await fetchWithRetry(`${FLOW_HOST}/api/some-endpoint`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json', accept: 'application/json' },
  body: JSON.stringify(payload),
});
if (!res.ok) throw new ApiError(`Request failed: ${res.status} ${res.statusText}`);

You can override behavior per call by passing a policy with custom limits or a retryOn(error, response) predicate.

5. Usage Examples

5.1 Validate Extension Is Installed

import * as vscode from 'vscode';

function ensureFlowExtension(): void {
  const ext = vscode.extensions.getExtension('ciandt.flow-authentication-provider');
  if (!ext) {
    vscode.window.showErrorMessage(
      'Flow Login extension not found. Please install "Flow Login" from the Marketplace.'
    );
    throw new Error('Missing dependency: ciandt.flow-authentication-provider');
  }
}

5.2 Initiate API-Key Login and Retrieve Token

import * as vscode from 'vscode';

async function loginAndGetApiKey(): Promise<string> {
  // Trigger the Flow API-key login command
  await vscode.commands.executeCommand('flow-authentication-provider.login');
  // Retrieve the API-key session (no automatic creation)
  const session = await vscode.authentication.getSession('flowauth.apikey', [], { createIfNone: false });
  if (!session) {
    throw new Error('Flow API-key session not found');
  }
  const { accessToken: apiKeyToken, clientId, clientSecret } = session;
  // You can now use apiKeyToken, clientId, and clientSecret as needed
  return apiKeyToken;
}

5.3 Initiate OAuth Login and Retrieve Token

import * as vscode from 'vscode';

async function loginAndGetOAuthToken(): Promise<string> {
  // Trigger the Flow OAuth login command
  await vscode.commands.executeCommand('flow-authentication-provider.oauth');
  // Retrieve the OAuth session
  const session = await vscode.authentication.getSession('flowauth.oauth', [], { createIfNone: false });
  if (!session) {
    throw new Error('Flow OAuth session not found');
  }
  return session.accessToken;
}

5.4 Retrieve OAuth Token (Exported API)

import * as vscode from 'vscode';

async function getFlowTokenViaExports(): Promise<string> {
  ensureFlowExtension();
  const ext = vscode.extensions.getExtension('ciandt.flow-authentication-provider')!;
  await ext.activate();
  const api = ext.exports as FlowLoginAPI;
  return api.getToken();
}

5.5 Listen for Session Changes

import * as vscode from 'vscode';

async function watchFlowSession(): Promise<void> {
  ensureFlowExtension();
  const ext = vscode.extensions.getExtension('ciandt.flow-authentication-provider')!;
  await ext.activate();
  const api = ext.exports as FlowLoginAPI;
  api.onDidChangeSession(() => {
    console.log('Flow login session has changed – you may need to re-fetch tokens.');
  });
}

6. Best Practices

  • extensionDependencies ensures activation order.
  • Cache tokens/keys in memory if you call them frequently.
  • Clean up any event listeners in your extension’s deactivate().
  • Handle user cancellations (they may refuse to sign in).
  • Use sensible scopes for OAuth (request only what you need).

You can now safely call Flow APIs or protected endpoints from any third-party extension by re-using the centralized login logic in ciandt.flow-authentication-provider.

  • Contact us
  • Jobs
  • Privacy
  • Manage cookies
  • Terms of use
  • Trademarks
© 2025 Microsoft