TeamsFx helps to reduce your tasks by using Microsoft Teams single sign-on (SSO) and accessing cloud resources down to single line statements with zero configuration. You can use TeamsFx SDK in the browser and Node.js environments. TeamsFx core functionalities can be accessed in client and server environments. You can write user authentication code for:
Teams tab
Teams bot
Azure Function
Prerequisites
You need to install the following tools and set up your development environment:
TeamsFx SDK is pre-configured in the scaffolded project using TeamsFx Toolkit or CLI.
For more information, see Teams app project.
Tip
The code snippets are updated for the latest TeamsFx SDK version 2.
Install the @microsoft/teamsfx package
Install the TeamsFx SDK for TypeScript or JavaScript with npm:
Bash
npm install @microsoft/teamsfx
TeamsFx core functionalities
TeamsFx class
TeamsFx class instance access all TeamsFx settings from the environment variables by default. You can set customized configuration values to override the default values. For more information, see override configuration for details.
When creating a TeamsFx instance, you need to specify the identity type.
The following list provides the two different type of identities:
User Identity: Represents the current user of Teams.
Application Identity: Represents the application itself.
Note
The TeamsFx constructors and methods aren't the same for these two identity types.
You can learn more about user identity and application identity in the following section:
User identity
Command
Description
new TeamsFx(IdentityType.User)
Application is authenticated as current Teams user.
TeamsFx:setSsoToken()
User identity in Node.js environment (without browser).
TeamsFx:getUserInfo()
To get user's basis information.
TeamsFx:login()
It's used to let user perform consent process, if you want to use SSO to get access token for certain OAuth scopes.
Note
You can access resources on behalf of current Teams user.
Application identity
Command
Description
new TeamsFx(IdentityType.App)
Application is authenticated as an application. The permission usually needs administrator's approval.
TeamsFx:getCredential()
It provides credential instances automatically corresponding to the identity type.
Note
You need admin consent for resources.
Credential
Credential classes implement the TokenCredential interface that is broadly used in Azure library APIs designed to provide access tokens for specific scopes. For more information on credential and auth flow related classes, see credential folder.
There are three credential classes to simplify authentication. Here's the corresponding scenarios for each credential class target:
User identity in browser environment
TeamsUserCredential represents Teams current user's identity. For the first time user's credentials are authenticated, then Teams SSO does the On-Behalf-Of flow for token exchange. SDK uses this credential when you choose user identity in the browser environment.
The following code is an example to create TeamsUserCredential:
Required configurations are initiateLoginEndpoint and clientId that's found inside type TeamsUserCredentialAuthConfig.
User identity in Node.js environment
OnBehalfOfUserCredential uses On-Behalf-Of flow and require Teams SSO token, in Azure Function or bot scenarios. TeamsFx SDK uses the following credential when you choose user identity in Node.js environment.
The following code is an example to create OnBehalfOfUserCredential:
Required configurations are authorityHost, tenantId, clientId, clientSecret, or certificateContent that's found inside type OnBehalfOfCredentialAuthConfig.
App identity in Node.js environment
AppCredential represents the app identity. You can use app identity when user isn't involved, for example, in a time-triggered automation job. TeamsFx SDK uses the following credential when you choose app identity in Node.js environment.
The following code is an example to create AppCredential:
TeamsBotSsoPrompt integrates with the bot framework. It simplifies the authentication process when you develop bot application and want to use the bot SSO.
The following code is an example to create TeamsBotSsoPrompt:
TeamsFx SDK provides several functions to ease the configuration for third-party libraries. They're located under core folder.
Microsoft Graph Service:createMicrosoftGraphClient, createMicrosoftGraphClientWithCredential, and MsGraphAuthProvider helps to create authenticated Graph instance.
Note
createMicrosoftGraphClient function has been deprecated. Its recommended that you to use createMicrosoftGraphClientWithCredential instead, for better coding experience.
SQL: The getTediousConnectionConfig returns a tedious connection config.
Required configuration:
If you want to use the user identity, then sqlServerEndpoint, sqlUsername, and sqlPassword are required.
If you want to use the MSI identity, then sqlServerEndpointand sqlIdentityId are required.
Note
The getTediousConnectionConfig function has been deprecated. Its recommended that you compose your own Tedious configuration for better flexibility.
Override configuration for TeamsFx class
Note
TeamsFx class has been deprecated. Use TeamsUserCredential, OnBehalfOfUserCredential, and AppCredential instead.
You can pass custom config when creating a new TeamsFx instance to override default configuration or set required fields when environment variables are missing.
For tab project
If you've created tab project using Microsoft Visual Studio Code Toolkit, the following config values are used from pre-configured environment variables:
apiEndpoint (REACT_APP_FUNC_ENDPOINT) // only used when there's a backend function
apiName (REACT_APP_FUNC_NAME) // only used when there's a backend function
For Azure Function or bot project
If you've created Azure Function or bot project using Visual Studio Code Toolkit, the following config values are used from pre-configured environment variables:
initiateLoginEndpoint (INITIATE_LOGIN_ENDPOINT)
authorityHost (M365_AUTHORITY_HOST)
tenantId (M365_TENANT_ID)
clientId (M365_CLIENT_ID)
clientSecret (M365_CLIENT_SECRET)
applicationIdUri (M365_APPLICATION_ID_URI)
apiEndpoint (API_ENDPOINT)
sqlServerEndpoint (SQL_ENDPOINT) // only used when there's an sql instance
sqlUsername (SQL_USER_NAME) // only used when there's an sql instance
sqlPassword (SQL_PASSWORD) // only used when there's an sql instance
sqlDatabaseName (SQL_DATABASE_NAME) // only used when there's an SQL instance
sqlIdentityId (IDENTITY_ID) // only used when there's an SQL instance
Error handling
Basic type of API error response is ErrorWithCode, which contains error code and error message. For example, to filter out specific error, you can use the following snippet:
TypeScript
try {
const teamsfx = new TeamsFx();
await teamsfx.login("User.Read");
} catch (err: unknown) {
if (err instanceof ErrorWithCode && err.code !== ErrorCode.ConsentFailed) {
throw err;
} else {
// Silently fail because user cancels the consent dialogreturn;
}
}
Note
TeamsFx class has been deprecated, and ErrorWithCode is not recommended. You can use TeamsUserCredential instead.
TypeScript
try {
const authConfig: TeamsUserCredentialAuthConfig = {
clientId: process.env.REACT_APP_CLIENT_ID,
initiateLoginEndpoint: process.env.REACT_APP_START_LOGIN_PAGE_URL,
};
const credential = new TeamsUserCredential(authConfig);
await credential.login("User.Read");
} catch (err: unknown) {
if (err instanceof ErrorWithCode && err.code !== ErrorCode.ConsentFailed) {
throw err;
} else {
// Silently fail because user cancels the consent dialogreturn;
}
}
If a credential instance is used in other library, such as Microsoft Graph, it's possible that an error is caught and transformed.
Microsoft Graph Scenarios
This section provides several code snippets for common scenarios that are related to the Microsoft Graph. In such scenarios, user can call APIs using different permissions in frontend or backend.
User delegate permission in frontend (Use TeamsUserCredential)
Use graph API in tab app
This code snippet shows you how to use TeamsUserCredential and createMicrosoftGraphClientWithCredential to get user profiles from Microsoft Graph in tab app. It also shows you how to catch and resolve a GraphError.
Use teamsUserCredential.login() to get user consent.
TypeScript
// Put these code in a call-to-action callback function to avoid browser blocking automatically showing up pop-ups.await teamsUserCredential.login(["User.Read"]); // Login with scope
You can initialize a TeamsFx instance and graph client and get information from Microsoft Graph by this client.
TypeScript
try {
const graphClient = createMicrosoftGraphClientWithCredential(teamsUserCredential, ["User.Read"]); // Initializes MS Graph SDK using our MsGraphAuthProviderconst profile = await graphClient.api("/me").get();
} catch (err: unknown) {
// ErrorWithCode is handled by Graph clientif (err instanceof GraphError && err.code?.includes(ErrorCode.UiRequiredError)) {
// Need to show login button to ask for user consent.
}
}
The Microsoft Graph Toolkit library is a collection of various authentication providers and UI components powered by Microsoft Graph.
The @microsoft/mgt-teamsfx-provider package exposes the TeamsFxProvider class that uses TeamsFx class to sign in users and acquire tokens to use with Microsoft Graph.
// Import the providers and credential at the top of the pageimport {Providers} from'@microsoft/mgt-element';
import {TeamsFxProvider} from'@microsoft/mgt-teamsfx-provider';
import {TeamsUserCredential} from"@microsoft/teamsfx";
const scope = ["User.Read"];
const teamsfx = new TeamsFx();
const provider = new TeamsFxProvider(teamsfx, scope);
Providers.globalProvider = provider;
You can use the teamsfx.login(scopes) method to get required access token.
TypeScript
// Put these code in a call-to-action callback function to avoid browser blocking automatically showing up pop-ups. await teamsfx.login(this.scope);
Providers.globalProvider.setState(ProviderState.SignedIn);
You can add any component in your HTML page or in your render() method with React to use the TeamsFx context to access Microsoft Graph.
dialogs.add(
new WaterfallDialog("taskNeedingLogin", [
async (step) => {
returnawait step.beginDialog("TeamsBotSsoPrompt");
},
async (step) => {
const token = step.result;
if (token) {
// ... continue with task needing access token ...
} else {
await step.context.sendActivity(`Sorry... We couldn't log you in. Try again later.`);
returnawait step.endDialog();
}
},
])
);
For more information on sample to use graph API in bot application, see bot-sso sample.
Use Graph API in Message Extension
The following code snippet shows how to override handleTeamsMessagingExtensionQuery that extends from TeamsActivityHandler, and use handleMessageExtensionQueryWithSSO provided by TeamsFx SDK to sign in to get an access token:
This code snippet shows you how to use CreateApiClient or axios library to call Azure Function, and how to call Graph API in Azure Function to get user profiles.
You can use CreateApiClient provided by TeamsFx sdk to call Azure Function:
TypeScript
asyncfunctioncallFunction() {
const authConfig: TeamsUserCredentialAuthConfig = {
clientId: process.env.REACT_APP_CLIENT_ID,
initiateLoginEndpoint: process.env.REACT_APP_START_LOGIN_PAGE_URL,
};
const teamsUserCredential = new TeamsUserCredential(authConfig);
// Create an API client by providing the token and endpoint.const apiClient = CreateApiClient(
"https://YOUR_API_ENDPOINT", // Create an API Client that uses SSO token to authenticate requestsnew BearerTokenAuthProvider(async () => (await teamsUserCredential.getToken(""))!.token) // Call API hosted in Azure Functions on behalf of user to inject token to request header
);
// Send a GET request to "RELATIVE_API_PATH", "/api/functionName" for example.const response = await apiClient.get("RELATIVE_API_PATH");
return response.data;
}
You can also use axios library to call Azure Function.
This section provides several code snippets for other scenarios that are related to Microsoft Graph. You can create API client in Bot or Azure Function and access SQL database in Azure Function.
Create API client to call existing API in Bot or Azure Function
This code snippet shows you how to call an existing API in bot by ApiKeyProvider.
TypeScript
// Create an API Key auth provider. In addition to APiKeyProvider, following auth providers are also available:// BearerTokenAuthProvider, BasicAuthProvider, CertificateAuthProvider.const authProvider = new ApiKeyProvider("YOUR_API_KEY_NAME",
"YOUR_API_KEY_VALUE",
ApiKeyLocation.Header
);
// Create an API client using above auth provider.// You can also implement AuthProvider interface and use it here.const apiClient = createApiClient(
"YOUR_API_ENDPOINT",
authProvider
);
// Send a GET request to "RELATIVE_API_PATH", "/api/apiname" for example.const response = await apiClient.get("RELATIVE_API_PATH");
Access SQL database in Azure Function
Use tedious library to access SQL and use DefaultTediousConnectionConfiguration that manages authentication. You can also compose connection config of other SQL libraries based on the result of sqlConnectionConfig.getConfig().
Set the connection configuration.
TypeScript
// Equivalent to:// const sqlConnectConfig = new DefaultTediousConnectionConfiguration({// sqlServerEndpoint: process.env.SQL_ENDPOINT,// sqlUsername: process.env.SQL_USER_NAME,// sqlPassword: process.env.SQL_PASSWORD,// });const teamsfx = new TeamsFx();
// If there's only one SQL databaseconst config = await getTediousConnectionConfig(teamsfx);
// If there are multiple SQL databasesconst config2 = await getTediousConnectionConfig(teamsfx, "your database name");
Connect to your database.
TypeScript
const connection = new Connection(config);
connection.on("connect", (error) => {
if (error) {
console.log(error);
}
});
Note
The getTediousConnectionConfig function has been deprecated, Its recommended that you compose your own tedious configuration for better flexibility.
For more information on sample to access SQL database in Azure Function, see share-now sample.
Advanced Customization
Configure log
You can set customer log level and redirect outputs when using this library.
Note
Logs are turned off by default, you can turn them on by setting log level.
Enable log by setting log level
When you set log level then Logging gets enabled. It prints log information to console by default.
Set log level using the following snippet:
TypeScript
// Only need the warning and error messages.
setLogLevel(LogLevel.Warn);
Note
You can redirect log output by setting custom logger or log function.
Redirect by setting custom logger
TypeScript
setLogLevel(LogLevel.Info);
// Set another logger if you want to redirect to Application Insights in Azure Function
setLogger(context.log);
Redirect by setting custom log function
TypeScript
setLogLevel(LogLevel.Info);
// Only log error message to Application Insights in bot application.
setLogFunction((level: LogLevel, message: string) => {
if (level === LogLevel.Error) {
this.telemetryClient.trackTrace({
message: message,
severityLevel: Severity.Error,
});
}
});
Note
Log functions don't take effect if you set a custom logger.
Upgrade to latest SDK version
If you're using the version of SDK that has loadConfiguration(), you can perform the following steps to upgrade to the latest SDK version:
Instead of calling loadConfiguration(), use the specific auth config classes to customize the settings for each credential type. For example, use AppCredentialAuthConfig for AppCredential, OnBehalfOfUserCredentialAuthConfig for OnBehalfOfUserCredential, and TeamsUserCredentialAuthConfig for TeamsUserCredential.
Replace new TeamsUserCredential() with new TeamsUserCredential(authConfig).
Replace new M365TenantCredential() with new AppCredential(authConfig).
Replace new OnBehalfOfUserCredential(ssoToken) with new OnBehalfOfUserCredential(authConfig).
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, see our contributor guide.
Platform Docs feedback
Platform Docs is an open source project. Select a link to provide feedback:
Learn how to build and distribute Microsoft Teams apps that retrieve user information using the Microsoft Graph API. Practice building and deploying apps in the guided project at the end of the learning path.
Demonstrate understanding of Microsoft 365, to deliver industry-leading productivity apps along with intelligent cloud services, and world-class security.
Learn Microsoft Teams JavaScript client library (TeamsJS SDK), which helps you build app experiences hosted in an in Teams, Microsoft 365, and Outlook.
Learn to get context for your tab, context of user, team, or company, access information, retrieve context in private or shared channels, and handle theme change.
Learn how to add cloud resources such as Azure Functions, Azure API Management and integrate API connections using Teams Toolkit in Visual Studio Code.