Share via


Authorization class

Class responsible for managing authorization and OAuth flows. Handles multiple OAuth providers and manages the complete authentication lifecycle.

Remarks

The Authorization class provides a centralized way to handle OAuth authentication flows within the agent application. It supports multiple authentication handlers, token exchange, on-behalf-of flows, and provides event handlers for success/failure scenarios.

Key features:

  • Multiple OAuth provider support
  • Token caching and exchange
  • On-behalf-of (OBO) token flows
  • Sign-in success/failure event handling
  • Automatic configuration from environment variables

Example usage:

const auth = new Authorization(storage, {
  'microsoft': {
    name: 'Microsoft',
    title: 'Sign in with Microsoft',
    text: 'Please sign in'
  }
});

auth.onSignInSuccess(async (context, state) => {
  await context.sendActivity('Welcome! You are now signed in.');
});

Constructors

Authorization(Storage, AuthorizationHandlers, UserTokenClient)

Creates a new instance of Authorization.

Properties

authHandlers

Dictionary of configured authentication handlers.

Methods

beginOrContinueFlow(TurnContext, TurnState<DefaultConversationState, DefaultUserState, DefaultTempState>, string, boolean)

Begins or continues an OAuth flow.

exchangeToken(TurnContext, string[], string)

Exchanges a token for a new token with different scopes.

getToken(TurnContext, string)

Gets the token for a specific auth handler.

onSignInFailure((context: TurnContext, state: TurnState<DefaultConversationState, DefaultUserState, DefaultTempState>, authHandlerId?: string, errorMessage?: string) => Promise<void>)

Sets a handler to be called when sign-in fails.

onSignInSuccess((context: TurnContext, state: TurnState<DefaultConversationState, DefaultUserState, DefaultTempState>, authHandlerId?: string) => Promise<void>)

Sets a handler to be called when sign-in is successfully completed.

signOut(TurnContext, TurnState<DefaultConversationState, DefaultUserState, DefaultTempState>, string)

Signs out the current user.

Constructor Details

Authorization(Storage, AuthorizationHandlers, UserTokenClient)

Creates a new instance of Authorization.

new Authorization(storage: Storage, authHandlers: AuthorizationHandlers, userTokenClient: UserTokenClient)

Parameters

storage
Storage

The storage system to use for state management.

authHandlers
AuthorizationHandlers

Configuration for OAuth providers.

userTokenClient
UserTokenClient

Remarks

The constructor initializes all configured auth handlers and sets up OAuth flows. It automatically configures handler properties from environment variables if not provided:

  • Connection name: {handlerId}_connectionName
  • Connection title: {handlerId}_connectionTitle
  • Connection text: {handlerId}_connectionText

Example usage:

const auth = new Authorization(storage, {
  'microsoft': {
    name: 'Microsoft',
    title: 'Sign in with Microsoft'
  },
  'google': {
    // Will use GOOGLE_connectionName from env vars
  }
});

Property Details

authHandlers

Dictionary of configured authentication handlers.

public authHandlers: AuthorizationHandlers

Property Value

Method Details

beginOrContinueFlow(TurnContext, TurnState<DefaultConversationState, DefaultUserState, DefaultTempState>, string, boolean)

Begins or continues an OAuth flow.

function beginOrContinueFlow(context: TurnContext, state: TurnState<DefaultConversationState, DefaultUserState, DefaultTempState>, authHandlerId: string, secRoute?: boolean): Promise<TokenResponse>

Parameters

context
TurnContext

The context object for the current turn.

state

TurnState<DefaultConversationState, DefaultUserState, DefaultTempState>

The state object for the current turn.

authHandlerId

string

ID of the auth handler to use.

secRoute

boolean

Returns

Promise<TokenResponse>

A promise that resolves to the token response from the OAuth provider.

Remarks

This method manages the complete OAuth authentication flow:

  • If no flow is active, it begins a new OAuth flow and shows the sign-in card
  • If a flow is active, it continues the flow and processes the authentication response
  • Handles success/failure callbacks and updates the sign-in state accordingly

The method automatically manages the sign-in state and continuation activities, allowing the conversation to resume after successful authentication.

Example usage:

const tokenResponse = await auth.beginOrContinueFlow(context, state, 'microsoft');
if (tokenResponse && tokenResponse.token) {
  // User is now authenticated
  await context.sendActivity('Authentication successful!');
}

exchangeToken(TurnContext, string[], string)

Exchanges a token for a new token with different scopes.

function exchangeToken(context: TurnContext, scopes: string[], authHandlerId: string): Promise<TokenResponse>

Parameters

context
TurnContext

The context object for the current turn.

scopes

string[]

Array of scopes to request for the new token.

authHandlerId

string

ID of the auth handler to use.

Returns

Promise<TokenResponse>

A promise that resolves to the exchanged token response.

Remarks

This method handles token exchange scenarios, particularly for on-behalf-of (OBO) flows. It checks if the current token is exchangeable (e.g., has audience starting with 'api://') and performs the appropriate token exchange using MSAL.

Example usage:

const exchangedToken = await auth.exchangeToken(
  context,
  ['https://graph.microsoft.com/.default'],
  'microsoft'
);

getToken(TurnContext, string)

Gets the token for a specific auth handler.

function getToken(context: TurnContext, authHandlerId: string): Promise<TokenResponse>

Parameters

context
TurnContext

The context object for the current turn.

authHandlerId

string

ID of the auth handler to use.

Returns

Promise<TokenResponse>

A promise that resolves to the token response from the OAuth provider.

Remarks

This method retrieves an existing token for the specified auth handler. The token may be cached and will be retrieved from the OAuth provider if needed.

Example usage:

const tokenResponse = await auth.getToken(context, 'microsoft');
if (tokenResponse.token) {
  console.log('User is authenticated');
}

onSignInFailure((context: TurnContext, state: TurnState<DefaultConversationState, DefaultUserState, DefaultTempState>, authHandlerId?: string, errorMessage?: string) => Promise<void>)

Sets a handler to be called when sign-in fails.

function onSignInFailure(handler: (context: TurnContext, state: TurnState<DefaultConversationState, DefaultUserState, DefaultTempState>, authHandlerId?: string, errorMessage?: string) => Promise<void>)

Parameters

handler

(context: TurnContext, state: TurnState<DefaultConversationState, DefaultUserState, DefaultTempState>, authHandlerId?: string, errorMessage?: string) => Promise<void>

The handler function to call on sign-in failure.

Remarks

This method allows you to register a callback that will be invoked whenever a user's authentication attempt fails. The handler receives the turn context, state, auth handler ID, and an optional error message describing the failure.

Common failure scenarios include:

  • User cancels the authentication process
  • Invalid credentials or expired tokens
  • Network connectivity issues
  • OAuth provider errors

Example usage:

auth.onSignInFailure(async (context, state, authHandlerId, errorMessage) => {
  await context.sendActivity(`Sign-in failed: ${errorMessage || 'Unknown error'}`);
  await context.sendActivity('Please try signing in again.');
});

onSignInSuccess((context: TurnContext, state: TurnState<DefaultConversationState, DefaultUserState, DefaultTempState>, authHandlerId?: string) => Promise<void>)

Sets a handler to be called when sign-in is successfully completed.

function onSignInSuccess(handler: (context: TurnContext, state: TurnState<DefaultConversationState, DefaultUserState, DefaultTempState>, authHandlerId?: string) => Promise<void>)

Parameters

handler

(context: TurnContext, state: TurnState<DefaultConversationState, DefaultUserState, DefaultTempState>, authHandlerId?: string) => Promise<void>

The handler function to call on successful sign-in.

Remarks

This method allows you to register a callback that will be invoked whenever a user successfully completes the authentication process. The handler receives the turn context, state, and the ID of the auth handler that was used.

Example usage:

auth.onSignInSuccess(async (context, state, authHandlerId) => {
  await context.sendActivity(`Welcome! You signed in using ${authHandlerId}.`);
  // Perform any post-authentication setup
});

signOut(TurnContext, TurnState<DefaultConversationState, DefaultUserState, DefaultTempState>, string)

Signs out the current user.

function signOut(context: TurnContext, state: TurnState<DefaultConversationState, DefaultUserState, DefaultTempState>, authHandlerId?: string): Promise<void>

Parameters

context
TurnContext

The context object for the current turn.

state

TurnState<DefaultConversationState, DefaultUserState, DefaultTempState>

The state object for the current turn.

authHandlerId

string

Optional ID of the auth handler to use for sign out. If not provided, signs out from all handlers.

Returns

Promise<void>

A promise that resolves when sign out is complete.

Remarks

This method clears the user's token and resets the authentication state. If no specific authHandlerId is provided, it signs out from all configured handlers. This ensures complete cleanup of authentication state across all providers.

Example usage:

// Sign out from specific handler
await auth.signOut(context, state, 'microsoft');

// Sign out from all handlers
await auth.signOut(context, state);