Skip to main content

Overview

The vscode.authentication namespace provides functions to register authentication providers and get authentication sessions for various services.

Getting Authentication Sessions

getSession

Get an existing authentication session or create a new one.
function getSession(
  providerId: string,
  scopes: readonly string[],
  options?: AuthenticationGetSessionOptions
): Thenable<AuthenticationSession | undefined>
providerId
string
required
The ID of the authentication provider (e.g., ‘github’, ‘microsoft’)
scopes
string[]
required
The list of scopes required for the session
options
AuthenticationGetSessionOptions
Options for getting the session (createIfNone, clearSessionPreference, silent)
Example:
import * as vscode from 'vscode';

// Get GitHub session with specific scopes
const session = await vscode.authentication.getSession(
  'github',
  ['user:email', 'repo'],
  { createIfNone: true }
);

if (session) {
  console.log(`Authenticated as: ${session.account.label}`);
  console.log(`Access token: ${session.accessToken}`);
}

Authentication Providers

registerAuthenticationProvider

Register an authentication provider.
function registerAuthenticationProvider(
  id: string,
  label: string,
  provider: AuthenticationProvider,
  options?: AuthenticationProviderOptions
): Disposable
Example:
class MyAuthProvider implements vscode.AuthenticationProvider {
  private _onDidChangeSessions = new vscode.EventEmitter<vscode.AuthenticationProviderAuthenticationSessionsChangeEvent>();
  readonly onDidChangeSessions = this._onDidChangeSessions.event;

  async getSessions(
    scopes?: readonly string[]
  ): Promise<vscode.AuthenticationSession[]> {
    // Return existing sessions
    return [];
  }

  async createSession(
    scopes: readonly string[]
  ): Promise<vscode.AuthenticationSession> {
    // Create new session
    const session: vscode.AuthenticationSession = {
      id: 'session-id',
      accessToken: 'access-token',
      account: {
        id: 'user-id',
        label: 'User Name'
      },
      scopes: scopes
    };
    
    this._onDidChangeSessions.fire({
      added: [session],
      removed: [],
      changed: []
    });
    
    return session;
  }

  async removeSession(sessionId: string): Promise<void> {
    // Remove session
  }
}

const provider = new MyAuthProvider();
vscode.authentication.registerAuthenticationProvider(
  'myAuth',
  'My Auth Provider',
  provider,
  { supportsMultipleAccounts: true }
);

Events

onDidChangeSessions

Fires when authentication sessions change.
const onDidChangeSessions: Event<AuthenticationSessionsChangeEvent>
Example:
vscode.authentication.onDidChangeSessions(event => {
  if (event.provider.id === 'github') {
    console.log('GitHub authentication sessions changed');
    // Refresh UI or re-authenticate
  }
});

Common Use Cases

GitHub Authentication

async function authenticateWithGitHub() {
  try {
    const session = await vscode.authentication.getSession(
      'github',
      ['repo', 'user:email'],
      { createIfNone: true }
    );

    if (session) {
      // Use session.accessToken to make API calls
      const response = await fetch('https://api.github.com/user', {
        headers: {
          'Authorization': `token ${session.accessToken}`
        }
      });
      const user = await response.json();
      console.log(`Logged in as: ${user.login}`);
    }
  } catch (error) {
    vscode.window.showErrorMessage('Failed to authenticate with GitHub');
  }
}

Microsoft Authentication

async function authenticateWithMicrosoft() {
  const session = await vscode.authentication.getSession(
    'microsoft',
    ['user.read'],
    { createIfNone: true }
  );

  if (session) {
    console.log(`Microsoft account: ${session.account.label}`);
    // Use session to access Microsoft Graph API
  }
}

Silent Authentication

// Try to get session without showing UI
const session = await vscode.authentication.getSession(
  'github',
  ['repo'],
  { 
    createIfNone: false,
    silent: true
  }
);

if (session) {
  console.log('Already authenticated');
} else {
  console.log('Not authenticated, user needs to sign in');
}

AuthenticationSession Interface

The session object returned by getSession contains:
interface AuthenticationSession {
  // Unique session identifier
  readonly id: string;
  
  // Access token for making API calls
  readonly accessToken: string;
  
  // Account information
  readonly account: AuthenticationSessionAccountInformation;
  
  // Scopes granted for this session
  readonly scopes: readonly string[];
}

interface AuthenticationSessionAccountInformation {
  // Account identifier
  readonly id: string;
  
  // Display label (e.g., username or email)
  readonly label: string;
}

Best Practices

Minimal Scopes

Request only the scopes your extension actually needs

Handle Failures

Always handle authentication failures gracefully

Secure Tokens

Never log or expose access tokens in your extension

Session Changes

Listen to onDidChangeSessions to handle account switches

Complete Example

import * as vscode from 'vscode';

export function activate(context: vscode.ExtensionContext) {
  // Monitor authentication changes
  context.subscriptions.push(
    vscode.authentication.onDidChangeSessions(event => {
      if (event.provider.id === 'github') {
        vscode.window.showInformationMessage(
          'GitHub authentication changed'
        );
      }
    })
  );

  // Command to authenticate
  const authenticate = vscode.commands.registerCommand(
    'myExtension.authenticate',
    async () => {
      try {
        const session = await vscode.authentication.getSession(
          'github',
          ['repo', 'user:email'],
          { createIfNone: true }
        );

        if (session) {
          vscode.window.showInformationMessage(
            `Authenticated as ${session.account.label}`
          );
          
          // Store session ID for later use
          await context.globalState.update('sessionId', session.id);
        }
      } catch (error) {
        vscode.window.showErrorMessage(
          'Authentication failed: ' + error
        );
      }
    }
  );

  context.subscriptions.push(authenticate);
}

Extensions API

Learn about extension management and inter-extension communication

Build docs developers (and LLMs) love