Skip to content

Add TeamsExtension sample #219

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 28 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
f378598
Add TeamsExtension sample
rido-min Apr 22, 2025
46317a7
Merge branch 'main' into users/rido/teams-samples
rido-min Apr 22, 2025
9400b77
Return Card on Selected Item
rido-min Apr 25, 2025
b2387f2
Merge branch 'main' into users/rido/teams-samples
rido-min Apr 25, 2025
455d362
Add NuGetPackageName check and update cardValue formatting
rido-min Apr 28, 2025
5b2d4ab
Merge branch 'users/rido/teams-samples' of https://github.com/microso…
rido-min Apr 28, 2025
3964448
check commandId
rido-min Apr 28, 2025
01637ed
Merge branch 'main' into users/rido/teams-samples
rido-min Apr 29, 2025
4efec1c
merge
rido-min May 5, 2025
2efb444
add Teams Sample to SLN
rido-min May 5, 2025
bd592bc
fix ns
rido-min May 5, 2025
f8ca766
Merge branch 'main' into users/rido/teams-samples
rido-min May 6, 2025
5f0577c
apply code style to teamsagent sample
rido-min May 6, 2025
7f62f93
Merge branch 'users/rido/teams-samples' of https://github.com/microso…
rido-min May 6, 2025
b47598f
Merge branch 'main' into users/rido/teams-samples
rido-min May 6, 2025
22aab35
Merge branch 'main' of https://github.com/microsoft/Agents-for-net in…
rido-min May 7, 2025
cb25cb8
Merge branch 'main' into users/rido/teams-samples
rido-min May 8, 2025
e2a3927
Merge branch 'users/rido/teams-samples' of https://github.com/microso…
rido-min May 8, 2025
08824e9
rm TeamsApplicationOptions
rido-min May 8, 2025
3927793
Merge branch 'main' of https://github.com/microsoft/Agents-for-net in…
rido-min May 8, 2025
c0be831
rm allowedcallers from aspnetExt
rido-min May 8, 2025
82cd143
Merge branch 'main' into users/rido/teams-samples
rido-min May 9, 2025
651b425
Merge branch 'main' of https://github.com/microsoft/Agents-for-net in…
rido-min May 13, 2025
4d3e7c4
merging
rido-min May 13, 2025
fcb461e
add teams sample to sln
rido-min May 13, 2025
445c6c2
Merge branch 'main' of https://github.com/microsoft/Agents-for-net in…
rido-min May 13, 2025
afe4cd7
Merge branch 'main' into users/rido/teams-samples
rido-min May 14, 2025
1fa65cd
Merge branch 'main' of https://github.com/microsoft/Agents-for-net in…
rido-min May 14, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions src/Microsoft.Agents.SDK.sln
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.2.32505.173
# Visual Studio Version 18
VisualStudioVersion = 18.0.10607.193 main
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Libraries", "Libraries", "{4269F3C3-6B42-419B-B64A-3E6DC0F1574A}"
EndProject
Expand Down Expand Up @@ -123,6 +123,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FullAuthentication", "sampl
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OBOAuthorization", "samples\Authorization\OBOAuthorization\OBOAuthorization.csproj", "{0E1394C7-045C-2BDC-65E8-D42B2F31EF46}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TeamsAgent", "samples\Teams\TeamsAgent\TeamsAgent.csproj", "{D6410977-B795-C315-CC94-C2482E84BB4A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -305,6 +307,10 @@ Global
{0E1394C7-045C-2BDC-65E8-D42B2F31EF46}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0E1394C7-045C-2BDC-65E8-D42B2F31EF46}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0E1394C7-045C-2BDC-65E8-D42B2F31EF46}.Release|Any CPU.Build.0 = Release|Any CPU
{D6410977-B795-C315-CC94-C2482E84BB4A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D6410977-B795-C315-CC94-C2482E84BB4A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D6410977-B795-C315-CC94-C2482E84BB4A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D6410977-B795-C315-CC94-C2482E84BB4A}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -367,6 +373,7 @@ Global
{E951C602-E9ED-F77D-8FC9-5272DB90D1DD} = {674A812C-7287-4883-97F9-697D83750648}
{A6785A2A-A4C2-8F38-E9BB-4C5FD229F1F9} = {674A812C-7287-4883-97F9-697D83750648}
{0E1394C7-045C-2BDC-65E8-D42B2F31EF46} = {0F9D3F0D-C131-4D3B-A86F-59CC781E8A02}
{D6410977-B795-C315-CC94-C2482E84BB4A} = {674A812C-7287-4883-97F9-697D83750648}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {F1E8E538-309A-46F8-9CE7-AEC6589FAE60}
Expand Down

This file was deleted.

2 changes: 1 addition & 1 deletion src/samples/FullAuthentication/AspNetExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public static void AddAgentAspNetAuthentication(this IServiceCollection services

if (!tokenValidationSection.Exists())
{
logger?.LogError("Missing configuration section '{tokenValidationSectionName}'. This section is required to be present in appsettings.json",tokenValidationSectionName);
logger?.LogError("Missing configuration section '{tokenValidationSectionName}'. This section is required to be present in appsettings.json", tokenValidationSectionName);
throw new InvalidOperationException($"Missing configuration section '{tokenValidationSectionName}'. This section is required to be present in appsettings.json");
}

Expand Down
213 changes: 213 additions & 0 deletions src/samples/Teams/TeamsAgent/AspNetExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,213 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using Microsoft.Agents.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using Microsoft.IdentityModel.Validators;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;

namespace TeamsAgent;

public static class AspNetExtensions
{
private static readonly ConcurrentDictionary<string, ConfigurationManager<OpenIdConnectConfiguration>> _openIdMetadataCache = new();

/// <summary>
/// Adds token validation typical for ABS/SMBA and agent-to-agent.
/// default to Azure Public Cloud.
/// </summary>
/// <param name="services"></param>
/// <param name="configuration"></param>
/// <param name="tokenValidationSectionName">Name of the config section to read.</param>
/// <param name="logger">Optional logger to use for authentication event logging.</param>
/// <remarks>
/// Configuration:
/// <code>
/// "TokenValidation": {
/// "Audiences": [
/// "{required:agent-appid}"
/// ],
/// "TenantId": "{recommended:tenant-id}",
/// "ValidIssuers": [
/// "{default:Public-AzureBotService}"
/// ],
/// "IsGov": {optional:false},
/// "AzureBotServiceOpenIdMetadataUrl": optional,
/// "OpenIdMetadataUrl": optional,
/// "AzureBotServiceTokenHandling": "{optional:true}"
/// "OpenIdMetadataRefresh": "optional-12:00:00"
/// }
/// </code>
///
/// `IsGov` can be omitted, in which case public Azure Bot Service and Azure Cloud metadata urls are used.
/// `ValidIssuers` can be omitted, in which case the Public Azure Bot Service issuers are used.
/// `TenantId` can be omitted if the Agent is not being called by another Agent. Otherwise it is used to add other known issuers. Only when `ValidIssuers` is omitted.
/// `AzureBotServiceOpenIdMetadataUrl` can be omitted. In which case default values in combination with `IsGov` is used.
/// `OpenIdMetadataUrl` can be omitted. In which case default values in combination with `IsGov` is used.
/// `AzureBotServiceTokenHandling` defaults to true and should always be true until Azure Bot Service sends Entra ID token.
/// </remarks>
public static void AddAgentAspNetAuthentication(this IServiceCollection services, IConfiguration configuration, string tokenValidationSectionName = "TokenValidation", ILogger logger = null!)
{
IConfigurationSection tokenValidationSection = configuration.GetSection(tokenValidationSectionName);
List<string> validTokenIssuers = tokenValidationSection.GetSection("ValidIssuers").Get<List<string>>()!;
List<string> audiences = tokenValidationSection.GetSection("Audiences").Get<List<string>>()!;

if (!tokenValidationSection.Exists())
{
logger?.LogError("Missing configuration section '{tokenValidationSectionName}'. This section is required to be present in appsettings.json", tokenValidationSectionName);
throw new InvalidOperationException($"Missing configuration section '{tokenValidationSectionName}'. This section is required to be present in appsettings.json");
}

// If ValidIssuers is empty, default for ABS Public Cloud
if (validTokenIssuers == null || validTokenIssuers.Count == 0)
{
validTokenIssuers =
[
"https://api.botframework.com",
"https://sts.windows.net/d6d49420-f39b-4df7-a1dc-d59a935871db/",
"https://login.microsoftonline.com/d6d49420-f39b-4df7-a1dc-d59a935871db/v2.0",
"https://sts.windows.net/f8cdef31-a31e-4b4a-93e4-5f571e91255a/",
"https://login.microsoftonline.com/f8cdef31-a31e-4b4a-93e4-5f571e91255a/v2.0",
"https://sts.windows.net/69e9b82d-4842-4902-8d1e-abc5b98a55e8/",
"https://login.microsoftonline.com/69e9b82d-4842-4902-8d1e-abc5b98a55e8/v2.0",
];

string? tenantId = tokenValidationSection["TenantId"];
if (!string.IsNullOrEmpty(tenantId))
{
validTokenIssuers.Add(string.Format(CultureInfo.InvariantCulture, AuthenticationConstants.ValidTokenIssuerUrlTemplateV1, tenantId));
validTokenIssuers.Add(string.Format(CultureInfo.InvariantCulture, AuthenticationConstants.ValidTokenIssuerUrlTemplateV2, tenantId));
}
}

if (audiences == null || audiences.Count == 0)
{
throw new ArgumentException($"{tokenValidationSectionName}:Audiences requires at least one value");
}

bool isGov = tokenValidationSection.GetValue("IsGov", false);
bool azureBotServiceTokenHandling = tokenValidationSection.GetValue("AzureBotServiceTokenHandling", true);

// If the `AzureBotServiceOpenIdMetadataUrl` setting is not specified, use the default based on `IsGov`. This is what is used to authenticate ABS tokens.
string? azureBotServiceOpenIdMetadataUrl = tokenValidationSection["AzureBotServiceOpenIdMetadataUrl"];
if (string.IsNullOrEmpty(azureBotServiceOpenIdMetadataUrl))
{
azureBotServiceOpenIdMetadataUrl = isGov ? AuthenticationConstants.GovAzureBotServiceOpenIdMetadataUrl : AuthenticationConstants.PublicAzureBotServiceOpenIdMetadataUrl;
}

// If the `OpenIdMetadataUrl` setting is not specified, use the default based on `IsGov`. This is what is used to authenticate Entra ID tokens.
string? openIdMetadataUrl = tokenValidationSection["OpenIdMetadataUrl"];
if (string.IsNullOrEmpty(openIdMetadataUrl))
{
openIdMetadataUrl = isGov ? AuthenticationConstants.GovOpenIdMetadataUrl : AuthenticationConstants.PublicOpenIdMetadataUrl;
}

TimeSpan openIdRefreshInterval = tokenValidationSection.GetValue("OpenIdMetadataRefresh", BaseConfigurationManager.DefaultAutomaticRefreshInterval);

_ = services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ClockSkew = TimeSpan.FromMinutes(5),
ValidIssuers = validTokenIssuers,
ValidAudiences = audiences,
ValidateIssuerSigningKey = true,
RequireSignedTokens = true,
};

// Using Microsoft.IdentityModel.Validators
options.TokenValidationParameters.EnableAadSigningKeyIssuerValidation();

options.Events = new JwtBearerEvents
{
// Create a ConfigurationManager based on the requestor. This is to handle ABS non-Entra tokens.
OnMessageReceived = async context =>
{
string authorizationHeader = context.Request.Headers.Authorization.ToString();

if (string.IsNullOrEmpty(authorizationHeader))
{
// Default to AadTokenValidation handling
context.Options.TokenValidationParameters.ConfigurationManager ??= options.ConfigurationManager as BaseConfigurationManager;
await Task.CompletedTask.ConfigureAwait(false);
return;
}

string[]? parts = authorizationHeader?.Split(' ');
if (parts?.Length != 2 || parts[0] != "Bearer")
{
// Default to AadTokenValidation handling
context.Options.TokenValidationParameters.ConfigurationManager ??= options.ConfigurationManager as BaseConfigurationManager;
await Task.CompletedTask.ConfigureAwait(false);
return;
}

JwtSecurityToken? token = new(parts[1]);
string issuer = token.Claims.FirstOrDefault(claim => claim.Type == AuthenticationConstants.IssuerClaim)?.Value!;

if (azureBotServiceTokenHandling && AuthenticationConstants.BotFrameworkTokenIssuer.Equals(issuer))
{
// Use the Azure Bot authority for this configuration manager
context.Options.TokenValidationParameters.ConfigurationManager = _openIdMetadataCache.GetOrAdd(azureBotServiceOpenIdMetadataUrl, key =>
{
return new ConfigurationManager<OpenIdConnectConfiguration>(azureBotServiceOpenIdMetadataUrl, new OpenIdConnectConfigurationRetriever(), new HttpClient())
{
AutomaticRefreshInterval = openIdRefreshInterval
};
});
}
else
{
context.Options.TokenValidationParameters.ConfigurationManager = _openIdMetadataCache.GetOrAdd(openIdMetadataUrl, key =>
{
return new ConfigurationManager<OpenIdConnectConfiguration>(openIdMetadataUrl, new OpenIdConnectConfigurationRetriever(), new HttpClient())
{
AutomaticRefreshInterval = openIdRefreshInterval
};
});
}

await Task.CompletedTask.ConfigureAwait(false);
},

OnTokenValidated = context =>
{
logger?.LogDebug("TOKEN Validated");
return Task.CompletedTask;
},
OnForbidden = context =>
{
logger?.LogWarning("Forbidden: {m}", context.Result.ToString());
return Task.CompletedTask;
},
OnAuthenticationFailed = context =>
{
logger?.LogWarning("Auth Failed {m}", context.Exception.ToString());
return Task.CompletedTask;
}
};
});
}
}
17 changes: 17 additions & 0 deletions src/samples/Teams/TeamsAgent/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using Microsoft.Agents.Builder;
using Microsoft.Agents.Hosting.AspNetCore;
using Microsoft.Agents.Storage;
using TeamsAgent;

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpClient();
builder.Services.AddAgentAspNetAuthentication(builder.Configuration);
builder.AddAgentApplicationOptions();
builder.AddAgent<TeamsAgent.TeamsAgent>();
builder.Services.AddSingleton<IStorage, MemoryStorage>();
WebApplication app = builder.Build();

app.MapPost("/api/messages",
(HttpRequest request, HttpResponse response, IAgentHttpAdapter adapter, IAgent agent, CancellationToken cancellationToken) =>
adapter.ProcessAsync(request, response, agent, cancellationToken));
app.Run();
Loading
Loading