-
Notifications
You must be signed in to change notification settings - Fork 49
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
Merged
Merged
Changes from 28 commits
Commits
Show all changes
39 commits
Select commit
Hold shift + click to select a range
f378598
Add TeamsExtension sample
rido-min 46317a7
Merge branch 'main' into users/rido/teams-samples
rido-min 9400b77
Return Card on Selected Item
rido-min b2387f2
Merge branch 'main' into users/rido/teams-samples
rido-min 455d362
Add NuGetPackageName check and update cardValue formatting
rido-min 5b2d4ab
Merge branch 'users/rido/teams-samples' of https://github.com/microso…
rido-min 3964448
check commandId
rido-min 01637ed
Merge branch 'main' into users/rido/teams-samples
rido-min 4efec1c
merge
rido-min 2efb444
add Teams Sample to SLN
rido-min bd592bc
fix ns
rido-min f8ca766
Merge branch 'main' into users/rido/teams-samples
rido-min 5f0577c
apply code style to teamsagent sample
rido-min 7f62f93
Merge branch 'users/rido/teams-samples' of https://github.com/microso…
rido-min b47598f
Merge branch 'main' into users/rido/teams-samples
rido-min 22aab35
Merge branch 'main' of https://github.com/microsoft/Agents-for-net in…
rido-min cb25cb8
Merge branch 'main' into users/rido/teams-samples
rido-min e2a3927
Merge branch 'users/rido/teams-samples' of https://github.com/microso…
rido-min 08824e9
rm TeamsApplicationOptions
rido-min 3927793
Merge branch 'main' of https://github.com/microsoft/Agents-for-net in…
rido-min c0be831
rm allowedcallers from aspnetExt
rido-min 82cd143
Merge branch 'main' into users/rido/teams-samples
rido-min 651b425
Merge branch 'main' of https://github.com/microsoft/Agents-for-net in…
rido-min 4d3e7c4
merging
rido-min fcb461e
add teams sample to sln
rido-min 445c6c2
Merge branch 'main' of https://github.com/microsoft/Agents-for-net in…
rido-min afe4cd7
Merge branch 'main' into users/rido/teams-samples
rido-min 1fa65cd
Merge branch 'main' of https://github.com/microsoft/Agents-for-net in…
rido-min 6e095b5
test attachments
rido-min a892f36
merging from main
rido-min 637d12e
add teams agent sample to the sln
rido-min 5f73efb
Merge remote-tracking branch 'origin' into users/rido/teams-samples
rido-min e86a813
Enhance build configs and improve error handling
rido-min cd01432
Add OnQueryLink handler for message extensions
rido-min d90be87
Merge branch 'main' of https://github.com/microsoft/Agents-for-net in…
rido-min ed3665b
Merge branch 'main' into users/rido/teams-samples
rido-min 3969454
Merge branch 'main' into users/rido/teams-samples
rido-min 8d2adca
Merge branch 'main' into users/rido/teams-samples
rido-min f43c3bc
Merge branch 'main' into users/rido/teams-samples
MattB-msft File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
31 changes: 0 additions & 31 deletions
31
src/libraries/Extensions/Microsoft.Agents.Extensions.Teams/App/TeamsApplicationOptions.cs
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
}; | ||
}); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.