在上一篇文章中,我們一步步從無到有在Microsoft Teams中開發了一個簡單的Outgoing Webhook,并和我們本地的Web API應用程序產生交互,總結起來的步驟大概如下:
- 導航到“團隊” Tab頁, 選中需要建立的Channel, 選中“應用”這個Tab,點擊最下方的“創建傳出webhook”
- 開發傳出webhook的后端服務
- 配置ngrok進行請求轉發
- Team中發送消息,后端程序響應消息
這篇文章我們一起來看看如何使用dotnet的模板來快速開發一個帶安全驗證機制的Outgoing Webhook
1. 運行ngrok,記下轉發的地址
2. 在teams里新建一個app,這次記下security token
具體的創建步驟見第一篇文章
3. 安裝dotnet的模板
因為Teams的模板默認沒有安裝,所以我們需要在dotnet里添加模板
c:\demo> dotnet new -i MicrosoftTeams.Templates
4. 使用模板創建Teams Outgoing Webhook項目
運行以下命令來在當前目錄下創建工程
c:\demo> dotnet new teamswebhook
使用VS code打開這個目錄,找到appsettings.cs
文件,修改配置節點TeamsAppSecurityToken
, 填入我們創建Webhook時生成的security token
{"Logging": {"LogLevel": {"Default": "Warning"}},"AllowedHosts": "*","TeamsAppSecurityToken": "aDpHmzCh+z9r57niKFCew1AeI6tGjway5TfACZC7L88="
}
5. 運行程序
c:\demo> dotnet run
返回到Teams的對話框中,我們發送一條消息,觀察Teams的消息返回
注意到消息正常返回,且提示我們嘗試輸入hero 或者 thumbnail
,那我們根據提示,分別發送hero和thumbnail
上面的整個過程就是我們基于Microsoft Teams的模板創建的整個可交互的Outgoing Webhook的應用,下面我們來分析下整個的代碼結構:
首先,看到Services
中定義的接口ITeamsAuthProvider.cs
:
public interface ITeamsAuthProvider
{/// <summary>/// Validates the specified authentication header value./// </summary>/// <param name="request">The HTTP request message.</param>/// <returns>/// Response containing result of validation./// </returns>TeamsAuthResponse Validate(HttpRequest request);
}
其中的Validate
方法用于對請求的授權認證,TeamsAuthProvider.cs
繼承ITeamsAuthProvider
,實現了Validate
?的認證授權邏輯。這個驗證用來確保這個請求是從微軟Teams的服務器發過來的,而不是其他惡意的程序發送的請求,從而確保的請求的發起源是受信任的。
接著看下MessagesController
中,GetMessage
這個Action,首先實現對請求授權的判斷,
var authResult = _teamsAuth.Validate(this.Request);
if (!authResult.AuthSuccessful)
{return new Activity(){Text = "You are not authorized to call into this end point."};
}
重點我們看下下面這段代碼,
Attachment attachment = null;
if (activity.Text.Contains("hero", StringComparison.InvariantCultureIgnoreCase))
{var card = CreateSampleHeroCard();attachment = new Attachment(){ContentType = HeroCard.ContentType,Content = card};
}
else if (activity.Text.Contains("thumbnail", StringComparison.InvariantCultureIgnoreCase))
{var card = CreateSampleThumbnailCard();attachment = new Attachment(){ContentType = ThumbnailCard.ContentType,Content = card};
}
從上面的代碼中看到,我們在Teams中發送hero
或者thumbnail
時,會看到響應的消息是一個帶有圖片的消息回復,具體的這種圖片消息, 我們可以簡單理解為是一種圖片附件的形式,我們來分析其中hero
圖片附件的代碼:
private HeroCard CreateSampleHeroCard()
{return new HeroCard(){Title = "Superhero",Subtitle = "An incredible hero",Text = "Microsoft Teams",Images = new List<CardImage>(){new CardImage(){Url = "https://github.com/tony-xia/microsoft-teams-templates/raw/master/images/cbd_after_sunset.jpg"}},Buttons = new List<CardAction>(){new CardAction(){Type = "openUrl",Title = "Visit",Value = "http://www.microsoft.com"}}};
}
可以比較清楚的看到,一些標題Title和顯示問題Text, 其中Image作為顯示圖片URL, 這里的Buttons
是這一種行為,當我們點擊時,跳轉到對應設置的網站,點擊可以看到跳轉到微軟的官網。
可以看到使用dotnet template來創建outgooing webhook項目方便快速,而且使用了card,使得返回的消息格式非常豐富。