Skip to main content

How to Turn On Token Validation in Development in the Microsoft 365 Agents SDK in C#

· 8 min read
Jagdish Kumawat
Founder @ Dewiride

An agent built with the Microsoft 365 Agents SDK checks the token on every incoming request, except when it runs in the Development environment. There, by default, it accepts requests without any token. One argument, forceEnable: true, keeps the check on everywhere.

When Teams sends your agent a message, the request carries an Authorization: Bearer token issued for your bot. Token validation checks that token before the agent sees the message: who signed it, who it's for (your bot's ID), and that it hasn't expired. Without it, anyone who can reach your /api/messages endpoint can post a message that claims to come from Teams.

The Agents SDK leaves that check to ASP.NET Core. Microsoft's migration guide: The Bot Framework SDK included incoming JSON Web Token (JWT) authentication in its hosting stack, but the Agents SDK leaves HTTP authentication to ASP.NET. Copy AspNetExtensions into your project to enable ASP.NET authentication for incoming requests. AddAgentAuthorization then decides whether that authentication is switched on. Its API reference describes the default: When null (the default), authorization is enabled in all environments except Development.

That default is convenient for a local test channel that sends no token. But once a dev tunnel makes your local agent public, Development is exactly where you want the check.

Syntax​

Syntax
builder.AddAgentAuthorization(<configure>, forceEnable: <true | false>);
PartWhat it is
AddAgentAuthorizationTurns token validation on or off for the agent's endpoints
<configure>A lambda that registers the ASP.NET Core authentication, such as b => b.AddAgentAspNetAuthentication() from AspNetExtensions.cs
forceEnableOptional. true validates in every environment, false in none. Leave it out to validate everywhere except Development

AddAgentAspNetAuthentication reads its settings from the TokenValidation section of the configuration:

Syntax
"TokenValidation": {
"Audiences": [ "<bot ID>" ],
"TenantId": "<tenant ID>"
}
SettingWhat it is
AudiencesWho the tokens must be issued for: your bot's ID, which is its Microsoft Entra app's client ID
TenantIdThe Microsoft Entra tenant of your bot's app registration

The Example​

A small echo agent, TokenCheck, answers You said: … to every message. It listens on http://localhost:3978. To act as someone without a token, a curl or PowerShell command posts it a message activity directly. The bot ID and tenant ID are shown as 22222222-2222-2222-2222-222222222222 and 11111111-1111-1111-1111-111111111111.

Prerequisites​

  • An ASP.NET Core agent that uses the Microsoft.Agents.Hosting.AspNetCore package, version 1.9.205.
  • Your bot's ID and your tenant ID, for the TokenValidation settings.

Step 1: Add AspNetExtensions.cs​

AspNetExtensions.cs is a sample file from the Agents SDK repository: it registers JWT bearer validation for tokens from Azure Bot Service and from other agents. Download the version that matches the SDK into your project folder:

Terminal
curl -sSLO https://raw.githubusercontent.com/microsoft/Agents-for-net/v1.9.205/src/samples/Shared/AspNetExtensions.cs

-O saves the file under its own name, -L follows redirects, and -sS hides the progress bar but still shows errors.

Both commands print nothing on success and leave AspNetExtensions.cs (31,188 bytes) in the folder. The class has no namespace, so Program.cs can use it without a using. It builds with just the Microsoft.Agents.Hosting.AspNetCore package.

Step 2: Add the TokenValidation Settings​

Add the section to appsettings.json, with your bot's ID and tenant ID:

appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"TokenValidation": {
"Audiences": [
"22222222-2222-2222-2222-222222222222"
],
"TenantId": "11111111-1111-1111-1111-111111111111"
}
}

These two values aren't secrets: they say which tokens to accept, not how to sign in.

Step 3: Register Authorization the Default Way​

The agent itself:

EchoAgent.cs
using Microsoft.Agents.Builder;
using Microsoft.Agents.Builder.App;
using Microsoft.Agents.Builder.State;
using Microsoft.Agents.Core.Models;

namespace TokenCheck;

public class EchoAgent : AgentApplication
{
public EchoAgent(AgentApplicationOptions options) : base(options)
{
OnActivity(ActivityTypes.Message, EchoAsync);
}

private Task EchoAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
=> turnContext.SendActivityAsync($"You said: {turnContext.Activity.Text}", cancellationToken: cancellationToken);
}

And Program.cs, first without forceEnable, as Microsoft's quickstart has it:

Program.cs
using Microsoft.Agents.Hosting.AspNetCore;
using Microsoft.Agents.Storage;
using TokenCheck;

var builder = WebApplication.CreateBuilder(args);

builder.AddAgentDefaults()
.AddAgent<EchoAgent>()
.AddAgentAuthorization(b => b.AddAgentAspNetAuthentication());
builder.Services.AddSingleton<IStorage, MemoryStorage>();

var app = builder.Build();

app.UseAgents();
app.MapDefaultAgentEndpoints();

app.Run();

UseAgents() adds ASP.NET Core's authentication and authorization middleware, and MapDefaultAgentEndpoints() maps /api/messages. When AddAgentAuthorization has switched validation on, the endpoint requires an authorized request; when it hasn't, the endpoint accepts anyone.

Step 4: Send a Request Without a Token in Development​

Save a message activity as activity.json:

activity.json
{
"type": "message",
"id": "1",
"channelId": "msteams",
"serviceUrl": "http://localhost:5299/",
"from": { "id": "user-1" },
"recipient": { "id": "agent" },
"conversation": { "id": "conversation-1" },
"text": "hello"
}

Start the agent. Its launch profile sets the environment to Development:

Terminal 1
dotnet run

Then post the activity, with no Authorization header at all:

Terminal 2
curl -s -o /dev/null -w "%{http_code}\n" -X POST http://localhost:3978/api/messages -H "Content-Type: application/json" --data @activity.json
Output
202

202 Accepted: the agent took the message. Its log says why:

Terminal 1
warn: Microsoft.Agents.Hosting.AspNetCore.CloudAdapter[4]
Anonymous access is enabled for channel: msteams.

Nothing checked who sent it. In Development, the default registered no authentication at all.

Step 5: Compare with Production​

Stop the agent with Ctrl+C and start it in the Production environment. --no-launch-profile skips the launch profile, which would set Development again, so the URL comes from ASPNETCORE_URLS:

Terminal 1
ASPNETCORE_ENVIRONMENT=Production ASPNETCORE_URLS=http://localhost:3978 dotnet run --no-launch-profile

The startup log shows Hosting environment: Production. Send the same request again from the second terminal:

Output
401

401 Unauthorized: in Production, the same code validates tokens, and a request without one is turned away.

Step 6: Validate in Development Too​

Stop the agent and add forceEnable: true to the call:

Program.cs
using Microsoft.Agents.Hosting.AspNetCore;
using Microsoft.Agents.Storage;
using TokenCheck;

var builder = WebApplication.CreateBuilder(args);

builder.AddAgentDefaults()
.AddAgent<EchoAgent>()
.AddAgentAuthorization(b => b.AddAgentAspNetAuthentication(), forceEnable: true);
builder.Services.AddSingleton<IStorage, MemoryStorage>();

var app = builder.Build();

app.UseAgents();
app.MapDefaultAgentEndpoints();

app.Run();

Program.cs of the TokenCheck agent: AddAgentDefaults, AddAgent EchoAgent, and AddAgentAuthorization with AddAgentAspNetAuthentication and forceEnable: true, then MemoryStorage, UseAgents, MapDefaultAgentEndpoints and Run

Run it in Development again with dotnet run, and send the request:

Output
401

Now Development rejects it too. The response carries WWW-Authenticate: Bearer, the standard HTTP way of saying a bearer token is required, and the log no longer mentions anonymous access. Real requests from Teams carry a valid token for your bot and pass.

Common Mistakes​

MistakeWhat happensDo this instead
Testing locally through a public dev tunnel with the defaultAnyone with the tunnel URL can post to your agentPass forceEnable: true
Leaving Audiences empty or with another app's IDValid tokens for your bot are rejectedUse your bot's ID
Calling UseAgents() after MapDefaultAgentEndpoints()The authentication middleware isn't in front of the endpointCall UseAgents() first

Troubleshooting​

SymptomLikely causeFix
Anonymous access is enabled for channel in the logValidation is off: Development and no forceEnablePass forceEnable: true
The Agents Playground gets 401It sends no token in its default modeRun it with authentication
The app stops at startup with an ArgumentExceptionAspNetExtensions found no TokenValidation sectionAdd the section to the configuration

FAQ​

Why is Development the exception?​

So that a new agent works with a local test channel straight away. Microsoft's quickstart says so: By default, token validation is disabled in Development mode. This is determined by AddAgentAuthorization and the forceEnable argument.

Can I validate in Production and Staging but not in Development?​

Yes: forceEnable takes any expression. The API reference gives forceEnable: !builder.Environment.IsDevelopment() && !builder.Environment.IsEnvironment("Staging") as an example of choosing environments yourself.

Does this protect my other endpoints?​

Only the ones MapDefaultAgentEndpoints() maps. Add RequireAuthorization() to any endpoint of your own that needs the same protection.

Conclusion​

AddAgentAuthorization(b => b.AddAgentAspNetAuthentication()) validates tokens everywhere except Development, where a request without a token gets 202. Add forceEnable: true, and Development answers 401 as Production does, so a dev tunnel never exposes an unprotected agent.

Additional Resources​