重要
TeamsFx SDK 将于 2025 年 9 月正式弃用,支持将持续到 2026 年 9 月。 建议规划到 Teams SDK 的过渡,以便在 Microsoft Teams 中生成代理。 若要跨其他 Microsoft 365 平台扩展代理的功能,请使用 Microsoft 365 智能体 SDK。
TeamsFx 通过使用 Microsoft Teams 单一登录 (SSO) 和访问云资源,以零配置访问单行语句,从而帮助减少任务。 可以在浏览器和 Node.js 环境中使用 TeamsFx SDK。 可以在客户端和服务器环境中访问 TeamsFx 核心功能。 可以为以下项编写用户身份验证代码:
- Teams 选项卡
- Teams 机器人
- Azure Function
先决条件
需要安装以下工具并设置开发环境:
| 安装 | 用于使用... | |
|---|---|---|
| Visual Studio Code | JavaScript、TypeScript 或 SharePoint 框架 (SPFx) 生成环境。 使用版本 1.55 或更高版本。 | |
| Microsoft 365 代理工具包 (以前称为 Teams 工具包) | 一个Microsoft Visual Studio Code扩展,用于为应用创建项目基架。 使用 4.0.0 版本。 | |
| Node.js | 后端 JavaScript 运行时环境。 有关详细信息,请参阅 项目类型的Node.js 版本兼容性表。 | |
| Microsoft Teams | Microsoft Teams,通过聊天、会议、通话等应用,在一个位置与你合作的每个人进行协作。 | |
| Microsoft Edge(推荐)或 Google Chrome | 包含开发人员工具的浏览器。 |
有关 Node.js 版本兼容性的详细信息,请参阅使用 Visual Studio Code 创建 Teams 应用的先决条件。
注意
如果项目已将相关包作为依赖项安装botbuilder,请确保它们版本相同。
必须具备以下方面的工作知识:
入门
使用 Microsoft 365 代理工具包 CLI (以前称为 TeamsFx 工具包或 CLI) ,在基架项目中预配置 TeamsFx SDK。 有关详细信息,请参阅 Teams 应用项目。
提示
将针对最新的 TeamsFx SDK 版本 2 更新代码片段。
安装包
从 npm 安装 @microsoft/m365agentstoolkit-cli,并运行 atk -h 以检查所有可用命令:
npm install -g @microsoft/m365agentstoolkit-cli
atk -h
TeamsFx 核心功能
TeamsFx 类
默认情况下,TeamsFx 类实例从环境变量访问所有 TeamsFx 设置。 可以设置自定义配置值以替代默认值。 有关详细信息,请参阅 重写配置 。 创建 TeamsFx 实例时,需要指定标识类型。
以下列表提供了两种不同类型的标识:
用户标识:表示 Teams 的当前用户。
应用程序标识:表示应用程序本身。
注意
对于这两种标识类型,TeamsFx 构造函数和方法不同。
可以在以下部分中详细了解用户标识和应用程序标识:
用户标识
| 命令 | 说明 |
|---|---|
new TeamsFx(IdentityType.User) |
应用程序作为当前 Teams 用户进行身份验证。 |
TeamsFx:setSsoToken() |
Node.js 环境(无浏览器)中的用户标识。 |
TeamsFx:getUserInfo() |
要获取用户的基础信息。 |
TeamsFx:login() |
如果要使用 SSO 获取某些 OAuth 作用域的访问令牌,则将其用于允许用户执行同意流程。 |
注意
可以代表当前 Teams 用户访问资源。
应用程序标识
| 命令 | 说明 |
|---|---|
new TeamsFx(IdentityType.App) |
应用程序作为应用程序进行身份验证。 权限通常需要管理员的批准。 |
TeamsFx:getCredential() |
它自动提供与标识类型对应的凭据实例。 |
注意
需要管理员同意以获取资源。
Credential
凭据类实现TokenCredential在设计为特定范围提供访问令牌的库 API Azure 广泛使用的接口。 有关凭据和身份验证流相关类的详细信息,请参阅 credential 文件夹。
有三个凭据类可以简化身份验证。 下面是每个凭据类目标的相应方案:
浏览器环境中的用户标识
TeamsUserCredential 表示 Teams 当前用户的标识。 首次对用户的凭据进行身份验证时,Teams SSO 会执行令牌交换的代理流。 在浏览器环境中选择用户标识时,SDK 使用此凭据。
以下代码是创建 TeamsUserCredential的示例:
const authConfig: TeamsUserCredentialAuthConfig = {
clientId: process.env.REACT_APP_CLIENT_ID,
initiateLoginEndpoint: process.env.REACT_APP_START_LOGIN_PAGE_URL,
};
const credential = new TeamsUserCredential(authConfig);
所需的配置是 initiateLoginEndpoint , clientId 在 类型 TeamsUserCredentialAuthConfig中找到。
Node.js 环境中的用户标识
OnBehalfOfUserCredentialAzure函数或机器人方案中,使用代表流并需要 Teams SSO 令牌。 在 Node.js 环境中选择用户标识时,TeamsFx SDK 使用以下凭据。
以下代码是创建 OnBehalfOfUserCredential的示例:
const oboAuthConfig: OnBehalfOfCredentialAuthConfig = {
authorityHost: process.env.M365_AUTHORITY_HOST,
clientId: process.env.M365_CLIENT_ID,
tenantId: process.env.M365_TENANT_ID,
clientSecret: process.env.M365_CLIENT_SECRET,
};
const oboCredential = new OnBehalfOfUserCredential(ssoToken, oboAuthConfig);
所需的配置是 authorityHost、 tenantId、 clientId、 clientSecret或 certificateContent ,在 类型 OnBehalfOfCredentialAuthConfig中找到。
Node.js 环境中的应用标识
AppCredential 表示应用标识。 当用户不涉及时,可以使用应用标识,例如,在时间触发的自动化作业中。 在 Node.js 环境中选择应用标识时,TeamsFx SDK 使用以下凭据。
以下代码是创建 AppCredential的示例:
const appAuthConfig: AppCredentialAuthConfig = {
authorityHost: process.env.M365_AUTHORITY_HOST,
clientId: process.env.M365_CLIENT_ID,
tenantId: process.env.M365_TENANT_ID,
clientSecret: process.env.M365_CLIENT_SECRET,
};
const appCredential = new AppCredential(appAuthConfig);
所需的配置为 authorityHost、 tenantId、 clientId、 clientSecret或 certificateContent ,这些配置位于 类型内 AppCredentialAuthConfig
机器人 SSO
机器人相关类存储在 机器人文件夹 下。
TeamsBotSsoPrompt 与机器人框架集成。 它简化了开发机器人应用程序并想要使用机器人 SSO 时的身份验证过程。
以下代码是创建 TeamsBotSsoPrompt的示例:
const TeamsBotSsoPromptId = "TEAMS_BOT_SSO_PROMPT";
const settings: TeamsBotSsoPromptSettings = {
scopes: ["User.Read"],
timeout: 900000,
endOnInvalidMessage: true,
};
const authConfig: OnBehalfOfCredentialAuthConfig = {
authorityHost: process.env.M365_AUTHORITY_HOST,
clientId: process.env.M365_CLIENT_ID,
tenantId: process.env.M365_TENANT_ID,
clientSecret: process.env.M365_CLIENT_SECRET,
};
const loginUrl = process.env.INITIATE_LOGIN_ENDPOINT;
const ssoPrompt = new TeamsBotSsoPrompt(authConfig, loginUrl, TeamsBotSsoPromptId, settings);
受支持的函数
TeamsFx SDK 提供多个函数,可用于简化第三方库的配置。 它们位于 核心文件夹下。
Microsoft Graph Service:
createMicrosoftGraphClient、createMicrosoftGraphClientWithCredential和MsGraphAuthProvider有助于创建经过身份验证的 Graph 实例。注意
createMicrosoftGraphClient函数已弃用。 建议改用createMicrosoftGraphClientWithCredential,以提供更好的编码体验。SQL:返回
getTediousConnectionConfig乏味的连接配置。所需配置:
- 如果要使用用户标识,则需要
sqlServerEndpoint、sqlUsername和sqlPassword。 - 如果要使用 MSI 标识,则需要
sqlServerEndpoint和sqlIdentityId。
注意
函数
getTediousConnectionConfig已弃用。 建议编写自己的 Tedious 配置,以提高灵活性。- 如果要使用用户标识,则需要
替代 TeamsFx 类的配置
注意
TeamsFx 类已弃用。 请改用 TeamsUserCredential、 OnBehalfOfUserCredential和 AppCredential 。
可以在创建新 TeamsFx 实例时传递自定义配置以替代默认配置,或者在缺少时 environment variables 设置必填字段。
对于选项卡项目
如果使用 Microsoft Visual Studio Code Toolkit 创建了选项卡项目,则会从预配置的环境变量使用以下配置值:
- authorityHost (REACT_APP_AUTHORITY_HOST)
- tenantId (REACT_APP_TENANT_ID)
- clientId (REACT_APP_CLIENT_ID)
- initiateLoginEndpoint (REACT_APP_START_LOGIN_PAGE_URL)
- applicationIdUri (REACT_APP_START_LOGIN_PAGE_URL)
- apiEndpoint (REACT_APP_FUNC_ENDPOINT) // 仅在存在后端函数时才使用
- apiName (REACT_APP_FUNC_NAME) // 仅在存在后端函数时才使用
对于Azure函数或机器人项目
如果已使用 Visual Studio Code Toolkit 创建Azure函数或机器人项目,则会从预配置的环境变量使用以下配置值:
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) // 仅在存在 sql 实例时才使用
sqlUsername (SQL_USER_NAME) // 仅在存在 sql 实例时才使用
sqlPassword (SQL_PASSWORD) // 仅在存在 sql 实例时才使用
sqlDatabaseName (SQL_DATABASE_NAME) // 仅在存在 SQL 实例时才使用
sqlIdentityId (IDENTITY_ID) // 仅在存在 SQL 实例时才使用
错误处理
API 错误响应的基本类型为 ErrorWithCode,其中包含错误代码和错误消息。 例如,要筛选出特定错误,可以使用以下代码片段:
try {
const atk = 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 dialog
return;
}
}
注意
TeamsFx 类已弃用, ErrorWithCode 不建议使用。 可以改用 TeamsUserCredential 。
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 dialog
return;
}
}
如果在其他库(如 Microsoft Graph)中使用了凭据实例,则可能捕获并转换了错误。
Microsoft Graph 方案
本部分为与 Microsoft Graph 相关的常见方案提供了多个代码片段。 在这种情况下,用户可以在前端或后端使用不同的权限调用 API。
前端中的用户委托权限 (使用
TeamsUserCredential)在选项卡应用中使用图形 API
此代码片段演示如何使用
TeamsUserCredential和createMicrosoftGraphClientWithCredential从选项卡应用中的 Microsoft Graph 获取用户配置文件。 它还演示如何捕获和解析GraphError。导入所需的类。
import { createMicrosoftGraphClientWithCredential, TeamsUserCredential, } from "@microsoft/teamsfx";创建
TeamsUserCredential实例。const authConfig: TeamsUserCredentialAuthConfig = { clientId: process.env.REACT_APP_CLIENT_ID!, initiateLoginEndpoint: process.env.REACT_APP_START_LOGIN_PAGE_URL!, }; const teamsUserCredential = new TeamsUserCredential(authConfig);使用
teamsUserCredential.login()获取用户同意。// 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可以初始化 TeamsFx 实例和图形客户端,并通过此客户端从 Microsoft Graph 获取信息。
try { const graphClient = createMicrosoftGraphClientWithCredential(teamsUserCredential, ["User.Read"]); // Initializes MS Graph SDK using our MsGraphAuthProvider const profile = await graphClient.api("/me").get(); } catch (err: unknown) { // ErrorWithCode is handled by Graph client if (err instanceof GraphError && err.code?.includes(ErrorCode.UiRequiredError)) { // Need to show login button to ask for user consent. } }
有关在选项卡应用中使用图形 API的示例的详细信息,请参阅 Graph Conector 应用示例。
与 Microsoft Graph 工具包集成
Microsoft Graph 工具包库是由 Microsoft Graph 提供支持的各种身份验证提供程序和 UI 组件的集合。
包
@microsoft/mgt-teamsfx-provider公开类,TeamsFxProvider该类使用TeamsFx类登录用户,并获取用于 Microsoft Graph 的令牌。可以安装以下必需的包:
npm install @microsoft/mgt-element @microsoft/mgt-teamsfx-provider @microsoft/teamsfx在组件内初始化提供程序。
// Import the providers and credential at the top of the page import {Providers} from '@microsoft/mgt-element'; import {TeamsFxProvider} from '@microsoft/mgt-teamsfx-provider'; import {TeamsUserCredential} from "@microsoft/teamsfx"; const scope = ["User.Read"]; const atk = new TeamsFx(); const provider = new TeamsFxProvider(teamsfx, scope); Providers.globalProvider = provider;可以使用
teamsfx.login(scopes)方法获取所需的访问令牌。// 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);可以使用 React 在 HTML 页或方法中添加
render()任何组件,TeamsFx以使用上下文访问 Microsoft Graph。<mgt-person query="me" view="threeLines"></mgt-person>public render(): void { return ( <div> <Person personQuery="me" view={PersonViewType.threelines}></Person> </div> ); }
有关初始化 TeamsFx 提供程序的示例的详细信息,请参阅 联系人导出程序示例。
后端中的用户委托权限 (使用
OnBehalfOfUserCredential)在机器人应用程序中使用图形 API
此代码片段演示如何使用
TeamsBotSsoPrompt设置对话框,然后登录 以获取访问令牌。初始化并添加到
TeamsBotSsoPrompt对话框集。const { ConversationState, MemoryStorage } = require("botbuilder"); const { DialogSet, WaterfallDialog } = require("botbuilder-dialogs"); const { TeamsBotSsoPrompt, OnBehalfOfCredentialAuthConfig, TeamsBotSsoPromptSettings } = require("@microsoft/teamsfx"); const convoState = new ConversationState(new MemoryStorage()); const dialogState = convoState.createProperty("dialogState"); const dialogs = new DialogSet(dialogState); const TeamsBotSsoPromptId = "TEAMS_BOT_SSO_PROMPT"; const settings: TeamsBotSsoPromptSettings = { scopes: ["User.Read"], timeout: 900000, endOnInvalidMessage: true, }; const authConfig: OnBehalfOfCredentialAuthConfig = { authorityHost: process.env.M365_AUTHORITY_HOST, clientId: process.env.M365_CLIENT_ID, tenantId: process.env.M365_TENANT_ID, clientSecret: process.env.M365_CLIENT_SECRET, }; const loginUrl = process.env.INITIATE_LOGIN_ENDPOINT; const ssoPrompt = new TeamsBotSsoPrompt(authConfig, loginUrl, TeamsBotSsoPromptId, settings); dialogs.add(ssoPrompt);启动对话框并登录。
dialogs.add( new WaterfallDialog("taskNeedingLogin", [ async (step) => { return await 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.`); return await step.endDialog(); } }, ]) );
有关在机器人应用程序中使用图形 API 的示例的详细信息,请参阅 bot-sso 示例。
在消息扩展中使用图形 API
以下代码片段演示如何重写
handleTeamsMessagingExtensionQuery从TeamsActivityHandler扩展的 ,并使用handleMessageExtensionQueryWithSSOTeamsFx SDK 提供的登录来获取访问令牌:const authConfig: OnBehalfOfCredentialAuthConfig = { authorityHost: process.env.M365_AUTHORITY_HOST, clientId: process.env.M365_CLIENT_ID, tenantId: process.env.M365_TENANT_ID, clientSecret: process.env.M365_CLIENT_SECRET, }; const loginUrl = process.env.INITIATE_LOGIN_ENDPOINT; public async handleTeamsMessagingExtensionQuery(context: TurnContext, query: any): Promise<any> { return await handleMessageExtensionQueryWithSSO(context, authConfig, loginUrl, 'User.Read', async (token: MessageExtensionTokenResponse) => { // ... continue to query with access token ... }); }有关在消息扩展中使用图形 API 的示例的详细信息,请参阅 message-extension-sso-sample。
在命令机器人中使用图形 API
此代码片段演示如何实现
TeamsFxBotSsoCommandHandler命令机器人调用Microsoft API。import { Activity, TurnContext } from "botbuilder"; import { CommandMessage, TriggerPatterns, createMicrosoftGraphClientWithCredential, TeamsFxBotSsoCommandHandler, TeamsBotSsoPromptTokenResponse, } from "@microsoft/teamsfx"; const authConfig: OnBehalfOfCredentialAuthConfig = { authorityHost: process.env.M365_AUTHORITY_HOST, clientId: process.env.M365_CLIENT_ID, tenantId: process.env.M365_TENANT_ID, clientSecret: process.env.M365_CLIENT_SECRET, }; const loginUrl = process.env.INITIATE_LOGIN_ENDPOINT; export class ProfileSsoCommandHandler implements TeamsFxBotSsoCommandHandler { triggerPatterns: TriggerPatterns = "profile"; async handleCommandReceived( context: TurnContext, message: CommandMessage, tokenResponse: TeamsBotSsoPromptTokenResponse, ): Promise<string | Partial<Activity> | void> { const oboCredential = new OnBehalfOfUserCredential(tokenResponse.ssoToken, oboAuthConfig); // Add scope for your Azure AD app. For example: Mail.Read, etc. const graphClient = createMicrosoftGraphClientWithCredential(oboCredential, ["User.Read"]); // Call graph api use `graph` instance to get user profile information const me = await graphClient.api("/me").get(); if (me) { // Bot will send the user profile info to user return `Your command is '${message.text}' and you're logged in as ${me.displayName}`; } else { return "Could not retrieve profile information from Microsoft Graph."; } } }有关如何在命令机器人中实现 SSO 命令处理程序的详细信息,请参阅 向 Teams 应用添加单一登录。 还有一个 command-bot-with-sso 示例项目,可以尝试 SSO 命令机器人。
在选项卡应用中调用Azure函数:代表流
此代码片段演示如何使用
CreateApiClient或axios库调用 Azure 函数,以及如何调用 Azure Function 中的 图形 API 以获取用户配置文件。可以使用
CreateApiClientTeamsFx sdk 提供的 调用 Azure 函数:async function callFunction() { 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 requests new 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; }还可以使用
axios库调用 Azure 函数。async function callFunction() { const authConfig: TeamsUserCredentialAuthConfig = { clientId: process.env.REACT_APP_CLIENT_ID, initiateLoginEndpoint: process.env.REACT_APP_START_LOGIN_PAGE_URL, }; const teamsUserCredential = new TeamsUserCredential(authConfig); const accessToken = await teamsUserCredential.getToken(""); // Get SSO token const endpoint = "https://YOUR_API_ENDPOINT"; const response = await axios.default.get(endpoint + "/api/" + functionName, { headers: { authorization: "Bearer " + accessToken.token, }, }); return response.data; }在 Azure Function 中代表用户调用图形 API以响应。
export default async function run( context: Context, req: HttpRequest, teamsfxContext: TeamsfxContext ): Promise<Response> { const res: Response = { status: 200, body: {},}; const authConfig: OnBehalfOfCredentialAuthConfig = { authorityHost: process.env.M365_AUTHORITY_HOST, clientId: process.env.M365_CLIENT_ID, tenantId: process.env.M365_TENANT_ID, clientSecret: process.env.M365_CLIENT_SECRET, }; const oboCredential = new OnBehalfOfUserCredential(tokenResponse.ssoToken, oboAuthConfig); // Query user's information from the access token. try { const currentUser: UserInfo = await oboCredential.getUserInfo(); if (currentUser && currentUser.displayName) { res.body.userInfoMessage = `User display name is ${currentUser.displayName}.`; } else { res.body.userInfoMessage = "No user information was found in access token."; } } catch (e) { } // Create a graph client to access user's Microsoft 365 data after user has consented. try { const graphClient: Client = createMicrosoftGraphClientWithCredential(oboCredential, [".default"]); const profile: any = await graphClient.api("/me").get(); res.body.graphClientMessage = profile; } catch (e) { } return res; }
有关在机器人应用程序中使用图形 API 的示例的详细信息,请参阅 hello-world-tab-with-backend 示例。
后端中的应用程序权限
在 Azure 函数中使用基于证书的身份验证
此代码片段演示如何使用基于证书的应用程序权限来获取可用于调用图形 API的令牌。
可以通过提供 来
PEM-encoded key certificate初始化appAuthConfig。const appAuthConfig: AppCredentialAuthConfig = { authorityHost: process.env.M365_AUTHORITY_HOST, clientId: process.env.M365_CLIENT_ID, tenantId: process.env.M365_TENANT_ID, certificateContent: 'PEM-encoded key certificate', };可以使用
AppCredential获取令牌。const appCredential = new AppCredential(appAuthConfig); const token = appCredential.getToken();
在 Azure 函数中使用客户端机密身份验证
此代码片段演示如何使用客户端机密应用程序权限获取用于调用图形 API的令牌。
可以通过提供 来
client secret初始化authConfig。const appAuthConfig: AppCredentialAuthConfig = { authorityHost: process.env.M365_AUTHORITY_HOST, clientId: process.env.M365_CLIENT_ID, tenantId: process.env.M365_TENANT_ID, clientSecret: process.env.M365_CLIENT_SECRET, };可以使用
authConfig获取令牌。const appCredential = new AppCredential(appAuthConfig); const token = appCredential.getToken();
有关在机器人应用程序中使用图形 API 的示例的详细信息,请参阅 hello-world-tab-with-backend 示例。
其他情景
本部分为与 Microsoft Graph 相关的其他方案提供了多个代码片段。 可以在机器人或 Azure 函数中创建 API 客户端,并在 Azure 函数中访问 SQL 数据库。
创建 API 客户端以调用机器人或 Azure 函数中的现有 API
此代码片段演示如何通过 ApiKeyProvider调用机器人中的现有 API。
// 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");
在 Azure 函数中访问 SQL 数据库
使用 tedious 库访问 SQL,并使用 DefaultTediousConnectionConfiguration 管理身份验证。 还可以基于 的结果编写其他 SQL 库的连接 sqlConnectionConfig.getConfig()配置。
设置连接配置。
// Equivalent to: // const sqlConnectConfig = new DefaultTediousConnectionConfiguration({ // sqlServerEndpoint: process.env.SQL_ENDPOINT, // sqlUsername: process.env.SQL_USER_NAME, // sqlPassword: process.env.SQL_PASSWORD, // }); const atk = new TeamsFx(); // If there's only one SQL database const config = await getTediousConnectionConfig(teamsfx); // If there are multiple SQL databases const config2 = await getTediousConnectionConfig(teamsfx, "your database name");连接到数据库。
const connection = new Connection(config); connection.on("connect", (error) => { if (error) { console.log(error); } });注意
函数
getTediousConnectionConfig已弃用,建议编写自己的繁琐配置,以提高灵活性。
有关在 Azure 函数中访问 SQL 数据库的示例的详细信息,请参阅 share-now 示例。
高级自定义
配置日志
使用此库时,可以设置客户日志级别并重定向输出。
注意
日志默认处于关闭状态,可以通过设置日志级别将其打开。
设置日志级别以启用日志
设置日志级别后,将启用日志记录。 默认情况下,它会将日志信息输出到控制台。
使用以下代码片段设置日志级别:
// Only need the warning and error messages.
setLogLevel(LogLevel.Warn);
注意
可以设置自定义记录器或日志函数,从而重定向日志输出。
设置自定义记录器以重定向
setLogLevel(LogLevel.Info);
// Set another logger if you want to redirect to Application Insights in Azure Function
setLogger(context.log);
设置自定义日志函数以重定向
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,
});
}
});
注意
如果设置自定义记录器,日志函数不会生效。
升级到最新 SDK 版本
如果使用的是具有 loadConfiguration()的 SDK 版本,可以执行以下步骤来升级到最新的 SDK 版本:
- 使用特定的身份验证配置类来自定义每种凭据类型的设置,而不是调用
loadConfiguration()。 例如,将 用于AppCredentialAuthConfigAppCredential、OnBehalfOfUserCredentialAuthConfig用于OnBehalfOfUserCredential和TeamsUserCredentialAuthConfig。TeamsUserCredential - 将
new TeamsUserCredential()替换为new TeamsUserCredential(authConfig)。 - 将
new M365TenantCredential()替换为new AppCredential(authConfig)。 - 将
new OnBehalfOfUserCredential(ssoToken)替换为new OnBehalfOfUserCredential(authConfig)。