You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Teams机器人/消息扩展应用实现GitHub OAuth认证?

GitHub OAuth Integration for Teams Bot/Message Extension (TypeScript + Teams Toolkit)

Prerequisites

  • Teams Toolkit v5+ installed in VS Code
  • GitHub account to create an OAuth app
  • Azure Bot Service resource linked to your Teams app (auto-created via Teams Toolkit)

Step 1: Create GitHub OAuth App

  • Go to GitHub Settings > Developer settings > OAuth Apps > New OAuth App
  • Set Homepage URL to your bot's base URL (pull from Teams Toolkit environment variables)
  • Set Authorization callback URL to https://<your-bot-domain>/api/oauth/callback
  • Save the generated Client ID and Client Secret for later use

Step 2: Configure OAuth Connection in Azure Bot Service

  • Open your Azure Bot Service resource in the Azure Portal
  • Navigate to Settings > OAuth Connection Settings > Add Connection
  • Fill in the details:
    • Connection name: GitHubOAuth
    • Service Provider: Generic OAuth 2.0
    • Client ID: Your GitHub OAuth app's Client ID
    • Client Secret: Your GitHub OAuth app's Client Secret
    • Authorization URL: https://github.com/login/oauth/authorize
    • Token URL: https://github.com/login/oauth/access_token
    • Scope: repo user (adjust based on your required GitHub API permissions)
  • Save the connection

Step 3: Update Project Configuration

  • In VS Code, open your Teams Toolkit project
  • Edit .env.local (or environment-specific .env file) to add:
    BOT_OAUTH_CONNECTION_NAME=GitHubOAuth
    GITHUB_CLIENT_ID=<your-github-client-id>
    
  • Ensure teamsapp.yml references your Azure Bot Service resource correctly (Teams Toolkit will sync the OAuth connection automatically)

Step 4: Implement OAuth Trigger in Bot/Message Extension

For Bots (Command-Based)

Add a command handler to trigger the OAuth flow:

import { TeamsFxBotCommandHandler, TriggerPatterns, TurnContext, CommandMessage, ActivityTypes, CardFactory } from "@microsoft/teamsfx";

export class GitHubAuthCommand implements TeamsFxBotCommandHandler {
  triggerPatterns: TriggerPatterns = "login github";

  async handleCommandReceived(context: TurnContext, message: CommandMessage) {
    const teamsfx = new TeamsFx(context);
    const loginUrl = await teamsfx.getLoginLink(context, process.env.BOT_OAUTH_CONNECTION_NAME!);
    
    return {
      type: ActivityTypes.Message,
      attachments: [
        CardFactory.heroCard(
          "GitHub Authentication",
          "Click below to log in with GitHub",
          [],
          { buttons: [CardFactory.openUrlButton("Log in with GitHub", loginUrl)] }
        )
      ]
    };
  }
}

Register this handler in your bot's initialization code.

For Message Extensions (Action Command)

Add authentication check and login prompt in your action handler:

import { TurnContext, MessagingExtensionActionResponse, CardFactory } from "botbuilder";
import { TeamsFx } from "@microsoft/teamsfx";

async handleActionInvoke(context: TurnContext, actionData: any): Promise<MessagingExtensionActionResponse> {
  const teamsfx = new TeamsFx(context);
  
  try {
    const tokenResponse = await teamsfx.getUserToken(process.env.BOT_OAUTH_CONNECTION_NAME!);
    
    if (!tokenResponse) {
      const loginUrl = await teamsfx.getLoginLink(context, process.env.BOT_OAUTH_CONNECTION_NAME!);
      const loginCard = CardFactory.heroCard(
        "Need GitHub Authentication",
        "Please log in to access GitHub features",
        [],
        { buttons: [CardFactory.openUrlButton("Log in", loginUrl)] }
      );
      
      return {
        composeExtension: {
          type: "result",
          attachmentLayout: "list",
          attachments: [loginCard]
        }
      };
    }

    // Proceed with authenticated logic here
    // ...

  } catch (error) {
    return {
      composeExtension: {
        type: "result",
        attachmentLayout: "list",
        attachments: [CardFactory.textCard("Authentication failed. Please try again.")]
      }
    };
  }
}

Step 5: Call GitHub API with Authenticated Token

Retrieve the token and use it to make GitHub API calls:

async getGitHubUserRepos(token: string) {
  const response = await fetch("https://api.github.com/user/repos", {
    headers: { Authorization: `token ${token}` }
  });
  
  if (!response.ok) throw new Error("Failed to fetch repositories");
  return await response.json();
}

// In your handler:
const tokenResponse = await teamsfx.getUserToken(process.env.BOT_OAUTH_CONNECTION_NAME!);
if (tokenResponse) {
  const repos = await this.getGitHubUserRepos(tokenResponse.token);
  // Format repos into cards and return to the user
}

Step 6: Test the Flow

  • Use Teams Toolkit's "Preview in Teams" feature to launch your app
  • Trigger the bot command or message extension action
  • Click the login button to authenticate with GitHub
  • Verify the app retrieves and displays GitHub data after successful auth

内容的提问来源于stack exchange,提问作者Comp_11

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 14:46:19