Bit of Technology

  • Archive
  • About Me
    • Advertise
    • Disclaimer
  • Speaking
  • Contact

Part 7: Securing an MCP Server with Microsoft Entra ID

October 13, 2026 By Taiseer Joudeh Leave a Comment

Share this:

  • Share on X (Opens in new window) X
  • Share on LinkedIn (Opens in new window) LinkedIn
  • Share on Reddit (Opens in new window) Reddit
  • Share on Facebook (Opens in new window) Facebook
  • Email a link to a friend (Opens in new window) Email

This is the seventh part of Building MCP Servers in .NET for AI Agents. The topics we’ll cover are:

  • What is the Model Context Protocol? An Introduction for .NET Developers
  • Building Your First MCP Server in C#
  • MCP Tools, Resources and Prompts in .NET
  • Wiring MCP Tools to Azure SQL and External APIs
  • Hosting an MCP Server in ASP.NET Core with Streamable HTTP
  • Building an MCP Client and AI Agent in .NET
  • Securing an MCP Server with Microsoft Entra ID (This Post)
  • Deploying an MCP Server to Azure Container Apps
  • Connecting an MCP Server to Microsoft Foundry Agent Service
  • Observability, Cost Control and MCP Security

The source code for this tutorial is available on GitHub.

Securing an MCP Server with Microsoft Entra ID

Our server has had no security since Part 5. Anyone who can reach it can call any tool. That includes submit_expense_report, which writes to the database.

Here is the request from Part 5. It still works today, with no credentials at all:

PowerShell
1
2
3
4
curl.exe -s -X POST http://localhost:5000/mcp `
  -H "Content-Type: application/json" `
  -H "Accept: application/json, text/event-stream" `
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'

That’s fine on your own machine. It won’t be fine in Part 8, when the server gets a public URL.

There’s another reason to do this before we deploy. Security changes how a tool is written. In this post we add approve_expense_report. It’s the first tool in the series that can’t work like the others, and seeing why is worth more than the setup around it.

Our server is the resource server

Our job here is smaller than you might think.

OAuth has three roles:

  1. The authorization server signs people in and hands out tokens.
  2. The client asks for a token.
  3. The resource server takes a token, checks it, and does the work.

Our MCP server is the resource server. Microsoft Entra ID is the authorization server. Our agent and VS Code are clients.

So we never see a password. We never show a sign-in page. We never create a token. Entra does all of that. We just check what it produced.

I’m spelling this out because the MCP authorization spec is long. Read it and you might think you have to build most of it. You don’t. Most of it tells client authors what to do.

Here’s what actually happens:

  1. A client calls our server with no token. We answer 401 and add a WWW-Authenticate header that points at a metadata document.
  2. The client fetches that document, from our server. It names the authorization server to use and the scopes that exist.
  3. The client goes to Entra, reads Entra’s own metadata to find the right endpoints, signs the user in, and gets a token back.
  4. The client calls us again with Authorization: Bearer. We check the token and run the tool.

Steps 1, 2 and 4 all happen on our server. Step 3 is between the client and Entra, and we play no part in it.

Notice there are two metadata documents in that list, and they belong to different people. Ours says where to go. Entra’s says how to talk to Entra. We only ever write the first one.

Two app registrations, and two different questions

We need two app registrations in Entra. People often try to do it with one, so it’s worth seeing why that doesn’t work.

The resource registration stands for our MCP server. It owns the name that tokens are issued for, the scopes that exist, and the roles a person can hold.

The client registration stands for the things that call us. That’s our .NET agent from Part 6 and VS Code. It holds the redirect URIs a browser is allowed to return to.

The resource registration holds two things that sound alike but aren’t. This difference comes up again and again in this post:

  1. A scope answers one question. May this client application talk to the expenses API on your behalf? It’s about the software in the middle.
  2. An app role answers a different one. Are you allowed to approve an expense report? It’s about the person.

You can hold the approver role and still get nothing, if the app you’re using was never granted the scope. An app can hold the scope and still not approve anything, if the person using it has no role. Both have to line up.

Registering with Microsoft Entra ID

Seven steps, all Azure CLI. Some of them have to run in a certain order, and I’ll say so when we get there.

After each step I show you where to look in the portal. The CLI changes things you can’t see, and looking at them afterwards is the quickest way to learn what an app registration holds.

Step 1: Set your variables

Two names and the URL our server will run on. That URL matters more than it looks.

PowerShell
1
2
3
4
5
6
$MCP_APP_NAME    = "BitOfTech Expenses MCP"
$CLIENT_APP_NAME = "BitOfTech Expenses Clients"
$MCP_LOCAL_URL   = "https://localhost:7040"
 
# Steps 3 to 6 write their request body to a file before sending it. This folder holds those files.
New-Item -ItemType Directory -Force -Path entra-setup | Out-Null

Note: that’s https, and our server has been on http://localhost:5000 since Part 5. An Application ID URI in Entra has to use api:// or https://, and ours is going to be the MCP endpoint, so the endpoint has to move. We do that in Step 8.

Step 2: Create both registrations

Both have to exist before we can connect them, because Step 3 needs the client’s ID.

PowerShell
1
2
3
4
5
6
7
8
9
10
11
12
13
14
$MCP_APP_ID = az ad app create --display-name $MCP_APP_NAME --query appId -o tsv
$MCP_OBJ_ID = az ad app show --id $MCP_APP_ID --query id -o tsv
 
$CLIENT_APP_ID = az ad app create `
  --display-name $CLIENT_APP_NAME `
  --is-fallback-public-client true `
  --public-client-redirect-uris "http://localhost:8080/callback" "http://127.0.0.1:33418" "https://vscode.dev/redirect" `
  --query appId -o tsv
 
az ad sp create --id $MCP_APP_ID
az ad sp create --id $CLIENT_APP_ID
 
Write-Output "MCP app:    $MCP_APP_ID"
Write-Output "Client app: $CLIENT_APP_ID"

Let’s review the parameters:

  1. --is-fallback-public-client true means this client can’t keep a secret. A console app and a code editor both run on the user’s machine, so anyone can read what’s inside them. Clients like this use PKCE instead of a secret.
  2. --public-client-redirect-uris lists where a browser may return to after sign-in. The first one is for our agent. The other two belong to VS Code and are fixed values that VS Code publishes.
  3. az ad sp create looks unnecessary. It isn’t. An app registration is the definition of an app. A service principal is that app inside your tenant. Role assignments and consent live on the service principal, so we need both objects.

Keep both IDs. They go into configuration later.

In the portal: open entra.microsoft.com, then Entra ID > App registrations > All applications. Both apps are listed with their Application (client) IDs.

Step 3: Create the scope, then pre-authorize the client

This takes two calls, because two Graph API rules get in each other’s way:

  1. A Graph PATCH replaces a whole property instead of merging into it. Send api with only the pre-authorization in it and you wipe out the scope you just created.
  2. Pre-authorization is checked against scopes that already exist. Create a scope and point at it in the same call, and Entra rejects it.

So we create the scope first, then send everything again with the pre-authorization added.

PowerShell
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
$SCOPE_ID = [guid]::NewGuid().ToString()
 
$scope = @{
  id                      = $SCOPE_ID
  value                   = "Expenses.Access"
  type                    = "User"
  isEnabled               = $true
  adminConsentDisplayName = "Access expense reports"
  adminConsentDescription = "Allows the app to read and manage expense reports on behalf of the signed-in user."
  userConsentDisplayName  = "Access your expense reports"
  userConsentDescription  = "Allows the app to read and manage your expense reports."
}
 
@{
  api = @{
    requestedAccessTokenVersion = 2
    oauth2PermissionScopes      = @($scope)
  }
} | ConvertTo-Json -Depth 6 -Compress | Set-Content -Path entra-setup/api-scope.json -Encoding ascii
 
az rest --method PATCH `
  --url "https://graph.microsoft.com/v1.0/applications/$MCP_OBJ_ID" `
  --headers "Content-Type=application/json" --body "@entra-setup/api-scope.json"
 
@{
  api = @{
    requestedAccessTokenVersion = 2
    oauth2PermissionScopes      = @($scope)
    preAuthorizedApplications   = @(
      @{ appId = $CLIENT_APP_ID; delegatedPermissionIds = @($SCOPE_ID) }
    )
  }
} | ConvertTo-Json -Depth 6 -Compress | Set-Content -Path entra-setup/api-preauth.json -Encoding ascii
 
az rest --method PATCH `
  --url "https://graph.microsoft.com/v1.0/applications/$MCP_OBJ_ID" `
  --headers "Content-Type=application/json" --body "@entra-setup/api-preauth.json"

What we have done here is the following:

  1. Built the JSON from a hashtable and piped it through ConvertTo-Json. Writing JSON inline on a PowerShell command line gets mangled by the quoting, the same problem we had with curl in Part 5. Writing it to a file and passing @file avoids all of that.
  2. Kept the scope in $scope so the two bodies can’t drift apart. The second call has to repeat everything from the first.
  3. Set requestedAccessTokenVersion to 2. More on this below.
  4. Pre-authorized the client. This is the resource saying “I trust this app, don’t ask the user to consent”. It matters because VS Code signs in with the account you’re already using and never shows a consent screen. Without pre-authorization there would be nowhere to click Accept.

About the token version. This one is easy to skip and awkward to debug. Microsoft’s guidance is that a resource app with a custom identifier URI should be on v2 tokens, which is what we’re about to give it in Step 4. When I ran this, az ad app create had already set it to 2. Check it rather than assuming. Apps made in the portal, and older ones, may not have it.

In the portal: App registrations > BitOfTech Expenses MCP > Manage > Manifest, then look at the api object.

Step 4: Set the Application ID URI

This is the name Entra knows our server by. When a client asks for a token it says “I want one for this”, and Entra looks for a registration with that exact name. If it doesn’t find one, there’s no token.

The name is the MCP endpoint, https://localhost:7040/mcp, not just the host. That catches people out, so it’s worth being clear about why.

The MCP authorization spec says the thing being protected is the endpoint a client calls. A client that reads our metadata document finds that address in it and asks Entra for a token for exactly that. So the registered name has to be the endpoint, character for character.

The same value is also the prefix of the scope. That’s why our agent requests https://localhost:7040/mcp/Expenses.Access and not just Expenses.Access.

So this one value does two jobs. A trailing slash, a missing /mcp or the wrong port breaks both, and the error you get won’t point you back here.

PowerShell
1
2
3
4
5
6
7
8
9
10
$MCP_RESOURCE = "$MCP_LOCAL_URL/mcp"
 
@{ identifierUris = @($MCP_RESOURCE) } | ConvertTo-Json -Compress |
  Set-Content -Path entra-setup/identifier.json -Encoding ascii
 
az rest --method PATCH `
  --url "https://graph.microsoft.com/v1.0/applications/$MCP_OBJ_ID" `
  --headers "Content-Type=application/json" --body "@entra-setup/identifier.json"
 
az ad app show --id $MCP_APP_ID --query identifierUris -o json

C#
1
2
3
[
  "https://localhost:7040/mcp"
]

Two Entra errors point back at this step. AADSTS500011 says the resource principal wasn’t found, which means the name the client asked for isn’t registered here. AADSTS9010010 says the resource parameter doesn’t match the requested scopes, which means the two values drifted apart. Both come from this one string being wrong somewhere.

In the portal: Manage > Expose an API. The Application ID URI is at the top, the scope from Step 3 is in the middle, and the pre-authorized client is at the bottom.

Step 5: Create the approver role

The scope we just made answers one question: may this app talk to the expenses API for you? It says nothing about whether you’re allowed to approve a report.

An app role is a label your tenant puts on a person. When they sign in, Entra writes that label into the token as a roles claim. Our server reads it from there. We never call Graph at request time, and the model in the middle never sees any of it.

PowerShell
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$ROLE_ID = [guid]::NewGuid().ToString()
 
@{
  appRoles = @(
    @{
      id                 = $ROLE_ID
      value              = "Expenses.Approver"
      displayName        = "Expenses Approver"
      description        = "Can approve expense reports submitted by other employees."
      allowedMemberTypes = @("User")
      isEnabled          = $true
    }
  )
} | ConvertTo-Json -Depth 5 -Compress | Set-Content -Path entra-setup/role.json -Encoding ascii
 
az rest --method PATCH `
  --url "https://graph.microsoft.com/v1.0/applications/$MCP_OBJ_ID" `
  --headers "Content-Type=application/json" --body "@entra-setup/role.json"

Two choices in there are worth a look:

  1. allowedMemberTypes is User, not Application. Application is for software that signs in as itself, with no person behind it. We’re describing a person who approves expenses, so we want User. A role can allow both, but there’s no reason to here.
  2. A role and not a security group. A group would work too. But a group belongs to your company and means whatever your company decided. An app role belongs to this application, ships with it, and means the same thing in any tenant it’s deployed to.

In the portal: Manage > App roles.

Step 6: Assign the role to yourself

Step 5 created the role. It didn’t give it to anyone. Creating a role and assigning it are two separate jobs, and they happen on two different objects.

PowerShell
1
2
3
4
5
6
7
8
9
10
11
$MCP_SP_ID = az ad sp show --id $MCP_APP_ID --query id -o tsv
$MY_OID    = az ad signed-in-user show --query id -o tsv
 
@{ principalId = $MY_OID; resourceId = $MCP_SP_ID; appRoleId = $ROLE_ID } |
  ConvertTo-Json -Compress | Set-Content -Path entra-setup/assign.json -Encoding ascii
 
az rest --method POST `
  --url "https://graph.microsoft.com/v1.0/users/$MY_OID/appRoleAssignments" `
  --headers "Content-Type=application/json" --body "@entra-setup/assign.json"
 
Write-Output "Your object id: $MY_OID"

Write down $MY_OID. It goes into the database in Step 12, and we come back to this assignment near the end of the post.

In the portal, and this one is in a different place. Role assignments don’t live on the app registration. Go to Entra ID > Enterprise applications, find BitOfTech Expenses MCP, then Manage > Users and groups.

This is the app registration and enterprise application split again. The registration defines the app. The enterprise application is that app inside your tenant, and assignments live there. Everyone gets caught by this once. The CLI hid it from us, because az ad sp create quietly made the second object back in Step 2.

Step 7: Let the client ask for the scope

We’re changing registrations here. Everything since Step 2 has been done to BitOfTech Expenses MCP, the resource. This is the first step that touches BitOfTech Expenses Clients, the caller.

Pre-authorization in Step 3 was the resource saying “I trust this client”. This is the other half. The client has to say which permission it wants. Both sides have to agree.

PowerShell
1
az ad app permission add --id $CLIENT_APP_ID --api $MCP_APP_ID --api-permissions "$SCOPE_ID=Scope"

Both registrations show up in that one line, which is a good way to see how they relate. Let’s review the parameters:

  1. --id $CLIENT_APP_ID is the registration we’re changing. The caller.
  2. --api $MCP_APP_ID is the registration we’re pointing at. The resource.
  3. --api-permissions "$SCOPE_ID=Scope" names the permission. Scope means a delegated permission, which acts for a signed-in user. The other option is Role, for an app that runs with no user at all.

There’s no admin-consent call here, because Step 3 already pre-authorized this client.

In the portal: App registrations > BitOfTech Expenses Clients > Manage > API permissions. You’ll see Expenses.Access listed under BitOfTech Expenses MCP, of type Delegated.

Note: the Status column is empty, and it should stay that way. Leave the Grant admin consent button alone. Step 3 pre-authorized this client, so there’s nothing left to consent to.

Then open Manage > Authentication to see the three redirect URIs from Step 2, with public client flows turned on. We come back to this page when we connect VS Code.

Protecting the server

Entra is ready. Now the code.

Step 8: Move to HTTPS

Entra accepts only two schemes for an Application ID URI, api:// and https://. The name we registered in Step 4 is the MCP endpoint, so the endpoint has to be on https. The server moves.

src/BitOfTech.Expenses.Mcp/Properties/launchSettings.json

C#
1
2
3
4
5
6
7
8
9
10
11
12
{
  "profiles": {
    "https": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "applicationUrl": "https://localhost:7040",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

If you’ve never trusted the local development certificate on this machine, do it now. Without it the agent’s HttpClient will refuse to connect:

C#
1
dotnet dev-certs https --trust

Windows shows a warning about installing a root certificate. That’s expected.

Step 9: Add the package and the settings

One package, to check JSON Web Tokens.

src/BitOfTech.Expenses.Mcp/BitOfTech.Expenses.Mcp.csproj, added to the existing ItemGroup:

C#
1
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.12" />

Then three settings. None of them are secret, which is the same argument we made about the connection string in Part 4.

src/BitOfTech.Expenses.Mcp/appsettings.json, next to ConnectionStrings:

C#
1
2
3
4
5
"Entra": {
  "TenantId": "your-tenant-id",
  "ClientId": "the MCP server app registration's client id",
  "ServerUrl": "https://localhost:7040"
}

Important note: ClientId here is the Application (client) ID of BitOfTech Expenses MCP, the resource registration. It’s the $MCP_APP_ID printed in Step 2, not $CLIENT_APP_ID.

Yes, the resource has a “client ID” too. That’s a confusing piece of Entra naming: every app registration gets one, whatever job that app does. It’s really just the registration’s ID.

In a v2 token the aud claim holds that GUID, not the Application ID URI. Reaching for the URI is the obvious mistake, and all you get back is a 401 with nothing in it.

Step 10: Set up token validation and publish the metadata

Two jobs in one file. It tells ASP.NET Core how to check an Entra token, and it fills in the metadata document clients read after a 401.

It gets its own file because it’s the part you’ll come back to when a token won’t validate, and it’s easier to find when it isn’t buried inside Program.cs.

src/BitOfTech.Expenses.Mcp/Auth/EntraAuthentication.cs

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
using Microsoft.AspNetCore.Authentication.JwtBearer;
using ModelContextProtocol.AspNetCore.Authentication;
using ModelContextProtocol.Authentication;
 
namespace BitOfTech.Expenses.Mcp.Auth;
 
public static class EntraAuthentication
{
    public const string CanApprovePolicy = "CanApprove";
 
    public static IServiceCollection AddEntraAuthentication(
        this IServiceCollection services,
        IConfiguration configuration)
    {
        var tenantId = configuration["Entra:TenantId"]!;
        var clientId = configuration["Entra:ClientId"]!;
        var serverUrl = configuration["Entra:ServerUrl"]!;
 
        var issuer = $"https://login.microsoftonline.com/{tenantId}/v2.0";
 
        // The protected resource is the MCP endpoint itself, not the host. This has to match the
        // Application ID URI from Step 4 exactly.
        var resource = $"{serverUrl}/mcp";
 
        services
            .AddAuthentication(options =>
            {
                // Two schemes doing two jobs. JWT bearer reads the token on every request.
                // The MCP scheme owns the 401, because only it knows how to write the
                // WWW-Authenticate header the protocol expects.
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = McpAuthenticationDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.Authority = issuer;
 
                // For a v2 token the audience is the resource's client id, not its App ID URI.
                options.Audience = clientId;
 
                options.TokenValidationParameters.ValidateIssuer = true;
                options.TokenValidationParameters.ValidIssuer = issuer;
            })
            .AddMcp(options =>
            {
                options.ResourceMetadata = new ProtectedResourceMetadata
                {
                    Resource = resource,
                    AuthorizationServers = { issuer },
                    // Entra resolves an unqualified scope name against Microsoft Graph, so the
                    // scope has to carry the Application ID URI that owns it.
                    ScopesSupported = [$"{resource}/Expenses.Access"],
                    BearerMethodsSupported = ["header"]
                };
            });
 
        services.AddAuthorizationBuilder()
            .AddPolicy(CanApprovePolicy, policy => policy.RequireRole("Expenses.Approver"));
 
        return services;
    }
}

What we have done here is the following:

  1. Registered two authentication schemes with two different jobs. DefaultAuthenticateScheme is JWT bearer, which reads and checks the token on every request. DefaultChallengeScheme is the MCP one, which runs when there’s no valid token. Splitting them is the trick here. ASP.NET Core already knows how to check an Entra token. The MCP package already knows how to write the 401 that MCP clients expect. We use each one for what it’s good at.
  2. Pointed Authority at the v2.0 issuer. The /v2.0 on the end isn’t optional. The v1 issuer is https://sts.windows.net/{tenant}/ and it won’t match the tokens we asked for.
  3. Set Audience to the client ID. See the note in Step 9.
  4. Published the resource metadata. ProtectedResourceMetadata becomes the JSON file clients read after a 401. We fill in four fields. The package serves the file and points at it from the 401 header.
  5. Added one authorization policy. CanApprove needs the Expenses.Approver role. Nothing uses it yet.

Note: ProtectedResourceMetadata.Resource is a string, and AuthorizationServers is a list of strings. They look like they should be Uri, and the compiler error when you try that is not very clear.

The helper that reads the caller’s identity goes next to it.

src/BitOfTech.Expenses.Mcp/Auth/CallerExtensions.cs

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
using System.Security.Claims;
 
namespace BitOfTech.Expenses.Mcp.Auth;
 
public static class CallerExtensions
{
    // Entra puts the stable user id in "oid". ASP.NET Core remaps it to this longer name unless
    // you turn claim mapping off, so check both rather than depending on that setting.
    private const string ObjectIdClaim = "oid";
    private const string ObjectIdClaimLong = "http://schemas.microsoft.com/identity/claims/objectidentifier";
 
    public static string? GetObjectId(this ClaimsPrincipal? user) =>
        user?.FindFirst(ObjectIdClaim)?.Value ?? user?.FindFirst(ObjectIdClaimLong)?.Value;
}

The oid claim is the stable ID for a user inside a tenant. We use it instead of the email address, because an administrator can change an email address.

Step 11: Require a token on the MCP endpoint

Step 10 built the authentication setup, but nothing uses it yet. The server still answers anyone who asks. This step adds that setup to the request pipeline, and tells the MCP endpoint to reject callers who have no token.

Four changes to Program.cs.

src/BitOfTech.Expenses.Mcp/Program.cs

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
builder.Services.AddEntraAuthentication(builder.Configuration);
 
builder.Services
    .AddMcpServer()
    .WithHttpTransport()
    .WithToolsFromAssembly()
    .WithResourcesFromAssembly()
    .WithPromptsFromAssembly()
    // Drops any tool, resource or prompt the caller is not allowed to use before the list is sent.
    .AddAuthorizationFilters();
 
var app = builder.Build();
 
app.UseAuthentication();
app.UseAuthorization();
 
app.MapMcp("/mcp").RequireAuthorization();
 
app.Run();

What we have done here is the following:

  1. AddEntraAuthentication is the file from Step 10.
  2. AddAuthorizationFilters() is the interesting one. It teaches the MCP server to filter its own tools by who is asking, so a tool you can’t use never shows up in tools/list. We use it near the end of the post.
  3. UseAuthentication and UseAuthorization in that order, like any ASP.NET Core app.
  4. RequireAuthorization() on the endpoint is the line that does the blocking. Without it, a caller with no token still gets through, and everything above it has no effect.

Testing that the server now needs a token

Start the server and make the Part 5 call again, this time against the new port.

C#
1
2
3
4
curl.exe -i -s -X POST https://localhost:7040/mcp `
  -H "Content-Type: application/json" `
  -H "Accept: application/json, text/event-stream" `
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'

C#
1
2
3
4
HTTP/1.1 401 Unauthorized
Content-Length: 0
Server: Kestrel
WWW-Authenticate: Bearer resource_metadata="https://localhost:7040/.well-known/oauth-protected-resource/mcp"

Look at the path in that header. It ends with /mcp, our endpoint path, tacked on after oauth-protected-resource. That’s how RFC 9728 handles a server that protects more than one thing, and it’s not the path most people would guess.

Fetch it and you get the file a client uses to find Entra:

C#
1
curl.exe -s https://localhost:7040/.well-known/oauth-protected-resource/mcp

PowerShell
1
2
3
4
5
6
{
  "resource": "https://localhost:7040/mcp",
  "authorization_servers": ["https://login.microsoftonline.com/<your-tenant-id>/v2.0"],
  "bearer_methods_supported": ["header"],
  "scopes_supported": ["https://localhost:7040/mcp/Expenses.Access"]
}

Those four fields are the whole public face of our security setup. A client that has never seen our server before can read them and work out what to do next.

Two of them are easy to get wrong, and both are worth a second look:

  1. resource has to match the URL this document was fetched from. RFC 9728 says so. We’re serving at /.well-known/oauth-protected-resource/mcp, so resource has to be https://localhost:7040/mcp. Name the host instead and a client that checks will refuse to continue.
  2. scopes_supported has to be fully qualified. A bare Expenses.Access looks tidier, but Entra resolves an unqualified scope name against Microsoft Graph, and you get told the scope doesn’t exist on a resource you’ve never heard of.

Teaching the agent to sign in

Now the client from Part 6 needs a token. The MCP C# SDK will run the whole OAuth flow for you. You set OAuth on the transport options with a client ID, a redirect URI and a scope, and it handles the discovery, the browser, PKCE and the refresh. That’s what I wrote first. Here’s what I got:

PowerShell
1
2
3
4
5
Unhandled exception. ModelContextProtocol.McpException: Failed to handle unauthorized response
with 'Bearer' scheme. Authorization server metadata from
'https://login.microsoftonline.com/<tenant>/v2.0/.well-known/openid-configuration'
does not include 'code_challenge_methods_supported'.
MCP clients require PKCE support and must refuse to proceed.

The client is right to refuse. The MCP spec says a client must not use an authorization server unless that server says it supports PKCE. Without PKCE, someone can steal the authorization code on its way back to the client.

Entra does support PKCE. It just doesn’t say so in its own metadata document, the Entra one from the start of this post. That document is the only one Entra publishes, so there is nothing else to point the client at, and no setting that changes it.

So we stop asking the SDK to do OAuth, and get the token ourselves. The transport accepts any headers we like, and our agent already uses Azure.Identity for the Foundry connection in Part 6. That means no new packages.

src/BitOfTech.Expenses.Agent/Program.cs, replacing the transport block:

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// The SDK can run the whole OAuth flow itself, but not against Entra: Entra's v2.0 metadata
// omits code_challenge_methods_supported, and an MCP client must refuse a server that does not
// advertise PKCE. So we sign in ourselves and hand the transport a bearer token.
var credential = new InteractiveBrowserCredential(new InteractiveBrowserCredentialOptions
{
    TenantId = configuration["Entra:TenantId"],
    ClientId = configuration["Entra:ClientId"],
    RedirectUri = new Uri(configuration["Entra:RedirectUri"]!)
});
 
var accessToken = await credential.GetTokenAsync(
    new TokenRequestContext([configuration["Entra:Scope"]!]));
 
await using var transport = new HttpClientTransport(new HttpClientTransportOptions
{
    Endpoint = new Uri(mcpEndpoint),
    Name = "bitoftech-expenses",
    AdditionalHeaders = new Dictionary<string, string>
    {
        ["Authorization"] = $"Bearer {accessToken.Token}"
    }
});

And the settings to go with it.

src/BitOfTech.Expenses.Agent/appsettings.json

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
  "Mcp": {
    "Endpoint": "https://localhost:7040/mcp"
  },
  "Entra": {
    "TenantId": "your-tenant-id",
    "ClientId": "the client app registration's client id",
    "RedirectUri": "http://localhost:8080/callback",
    "Scope": "https://localhost:7040/mcp/Expenses.Access"
  },
  "Foundry": {
    "Endpoint": "https://aif-bitoftech-expenses-tj01.cognitiveservices.azure.com/",
    "Deployment": "expenses-chat"
  }
}

Two things to watch here:

  1. ClientId is the client registration this time, not the resource one. The server’s settings name the resource. The agent’s settings name the caller. Same property name, two different GUIDs, and swapping them gives you a 401 with no explanation.
  2. Scope starts with the Application ID URI. That’s the second job the URI does, from Step 4.

Run the agent and a browser opens. Sign in, and it connects.

This works out quite neatly. The agent already used Azure.Identity to reach the model. Now it uses the same library to reach our server. What we lose is token refresh. A console app that runs for a few minutes doesn’t need it. A long running service would.

Nothing else in the agent changed. ToolLoop.cs from Part 6 never learns that tokens exist.

Connecting a caller to an employee

Until now our tools trusted whatever employee name the model sent. That won’t work for an approval. The server needs its own answer to “who is asking?”.

The token gives us an oid. The database has employees. Something has to join the two.

Step 12: One column and one new employee

src/BitOfTech.Expenses.Mcp/Models/Employee.cs

C#
1
2
3
// The Entra ID object id (oid claim) of the person this row represents, when they have a sign-in.
// Deliberately not the email, which an administrator can change.
public string? EntraObjectId { get; set; }

It’s nullable on purpose. Most of our employees are just rows in a table with no way to sign in. Real systems look like that too.

While we’re here, an approval that records nothing isn’t much of an approval.

src/BitOfTech.Expenses.Mcp/Models/ExpenseReport.cs

C#
1
2
3
public int? ApprovedByEmployeeId { get; set; }
 
public DateOnly? ApprovedOn { get; set; }

Then the mapping and a fourth employee.

src/BitOfTech.Expenses.Mcp/Data/ExpensesDbContext.cs

C#
1
2
3
4
5
6
7
modelBuilder.Entity<Employee>(entity =>
{
    entity.Property(e => e.Name).HasMaxLength(200).IsRequired();
    entity.Property(e => e.Email).HasMaxLength(320).IsRequired();
    entity.Property(e => e.EntraObjectId).HasMaxLength(36);
    entity.HasIndex(e => e.EntraObjectId).IsUnique().HasFilter("[EntraObjectId] IS NOT NULL");
});

C#
1
2
3
4
5
modelBuilder.Entity<Employee>().HasData(
    new Employee { Id = 1, Name = "Sara Haddad", Email = "sara.haddad@bitoftech.net" },
    new Employee { Id = 2, Name = "Omar Nasser", Email = "omar.nasser@bitoftech.net" },
    new Employee { Id = 3, Name = "Lina Farah", Email = "lina.farah@bitoftech.net" },
    new Employee { Id = 4, Name = "Taiseer Joudeh", Email = "taiseer.joudeh@bitoftech.net" });

The filtered unique index is worth copying. Two employees must never share one Entra account. But plenty of rows have no account at all, and a plain unique index would reject the second empty one. The IS NOT NULL filter allows both.

Create and apply the migration:

C#
1
2
dotnet ef migrations add AddApprovalAndEntraObjectId --project src/BitOfTech.Expenses.Mcp
dotnet ef database update --project src/BitOfTech.Expenses.Mcp

Then link your own account to employee 4, using the object id from Step 6:

C#
1
2
3
UPDATE Employees
SET EntraObjectId = 'your-object-id'
WHERE Email = 'taiseer.joudeh@bitoftech.net';

That one statement is what makes the next section work. You are now employee 4. Employees 1 to 3 are other people.

The tool with no approverName

Here’s the tool this whole post is about.

Start with what it doesn’t take. There’s no approverName parameter, and there can’t be one. If the approver was a parameter, the model would fill it in, and anyone could say “approve report 1003 as Taiseer Joudeh” and get away with it.

You can talk a model into passing any string you like. You can’t talk it into producing an object id signed by Entra.

Step 13: Add the approval tool

src/BitOfTech.Expenses.Mcp/Tools/ExpenseTools.cs

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
[McpServerTool(Name = "approve_expense_report")]
[Authorize(Policy = EntraAuthentication.CanApprovePolicy)]
[Description("Approves an expense report that is waiting for approval. The approver is always the signed in user, so never ask who is approving and never pass a name. Only a report that is currently Submitted can be approved, and approval cannot be undone.")]
public async Task<ExpenseReportDetail> ApproveExpenseReportAsync(
    RequestContext<CallToolRequestParams> context,
    [Description("The id of the submitted expense report to approve.")] int reportId,
    CancellationToken cancellationToken = default)
{
    // The caller comes from the validated token, never from a tool argument. A model can be
    // talked into passing any name you like, but it cannot mint an oid.
    var objectId = context.User.GetObjectId()
        ?? throw new McpException("The signed in user has no object id, so the approver cannot be identified.");
 
    var approver = await db.Employees
        .Where(e => e.EntraObjectId == objectId)
        .Select(e => new { e.Id, e.Name })
        .FirstOrDefaultAsync(cancellationToken)
        ?? throw new McpException(
            "The signed in user is not linked to an employee record, so they cannot approve reports.");
 
    var report = await db.Reports.FirstOrDefaultAsync(r => r.Id == reportId, cancellationToken)
        ?? throw new McpException(
            $"No expense report found with id {reportId}. Call search_expense_reports to find valid ids.");
 
    if (report.EmployeeId == approver.Id)
    {
        throw new McpException(
            $"Report {reportId} belongs to {approver.Name}, who is the signed in user. Nobody can approve their own expense report.");
    }
 
    if (report.Status is not ExpenseReportStatus.Submitted)
    {
        throw new McpException(
            $"Report {reportId} is {report.Status}, and only a Submitted report can be approved.");
    }
 
    report.Status = ExpenseReportStatus.Approved;
    report.ApprovedByEmployeeId = approver.Id;
    report.ApprovedOn = DateOnly.FromDateTime(DateTime.UtcNow);
 
    await db.SaveChangesAsync(cancellationToken);
 
    return await db.ReportDetail(reportId).FirstAsync(cancellationToken);
}

What we have done here is the following:

  1. Taken RequestContext<CallToolRequestParams> as the first parameter. The SDK fills this in and hides it from the model, so it never appears in the tool’s schema. context.User is a ClaimsPrincipal built from the token we checked.
  2. Put [Authorize] on the method, using the policy from Step 10. It’s ordinary ASP.NET Core authorization, applied to an MCP tool.
  3. Found the employee by oid. A signed-in user who isn’t an employee gets refused here. That’s a real case, since plenty of people in a tenant have no expense record.
  4. Refused self-approval before checking the status. The order matters for the message. Telling someone the report is theirs is more useful than telling them it’s the wrong status.
  5. Recorded who approved it and when.

Every refusal throws McpException. That’s the rule from Part 3: only this exception type has its message sent back to the model, so the model can tell the user what went wrong.

Trying it both ways

Start the server and the agent, then create something of your own to approve:

PowerShell
1
2
3
4
5
6
7
8
9
10
> Create an expense report for Taiseer Joudeh called Lisbon partner summit, in EUR.
  Two items: return flight 310.00 on 2026-09-18 and hotel for one night 145.00 on 2026-09-18.
  -> create_expense_report(employeeName: Taiseer Joudeh, title: Lisbon partner summit, ...)
Created draft expense report 1012 for Taiseer Joudeh.
 
Would you like me to submit it?
 
> yes
  -> submit_expense_report(reportId: 1012)
Submitted report 1012.

Now approve someone else’s report:

PowerShell
1
2
3
4
> Approve Omar's London offsite report
  -> search_expense_reports(employeeName: Omar, currentStatus: Submitted)
  -> approve_expense_report(reportId: 1003)
Approved report 1003, London team offsite.

And now your own:

PowerShell
1
2
3
4
5
6
> Approve the Lisbon partner summit report
  -> search_expense_reports(employeeName: Taiseer Joudeh, currentStatus: Submitted)
  -> approve_expense_report(reportId: 1012)
  <- "Report 1012 belongs to Taiseer Joudeh, who is the signed in user..."
I can't approve it: the tool says report 1012 belongs to Taiseer Joudeh, and nobody
can approve their own expense report.

Same tool, same permission, same model, same conversation. The only difference is whose report it is. The server worked that out from the token, not from anything the model said.

Showing each caller only the tools they can use

Refusing a call works. Never offering the tool is better.

There are two reasons for that. Every tool description is sent to the model on every request, so each one costs tokens. And a tool the caller is not allowed to use is a tool the model can waste a turn on.

AddAuthorizationFilters() from Step 11 deals with both. It runs the same [Authorize] policies against tools/list, and leaves out anything that fails.

We can see it work by taking the role away from ourselves. This is Step 6 in reverse:

PowerShell
1
2
3
4
5
6
7
8
9
10
11
12
13
# Your shell has probably been restarted since Step 6, so read these back rather than reusing them.
$MCP_APP_ID = az ad app list --display-name "BitOfTech Expenses MCP" --query "[0].appId" -o tsv
$MY_OID     = az ad signed-in-user show --query id -o tsv
 
$ROLE_ID = az ad app show --id $MCP_APP_ID `
  --query "appRoles[?value=='Expenses.Approver'].id | [0]" -o tsv
 
$ASSIGNMENT_ID = az rest --method GET `
  --url "https://graph.microsoft.com/v1.0/users/$MY_OID/appRoleAssignments" `
  --query "value[?appRoleId=='$ROLE_ID'].id | [0]" -o tsv
 
az rest --method DELETE `
  --url "https://graph.microsoft.com/v1.0/users/$MY_OID/appRoleAssignments/$ASSIGNMENT_ID"

Restart the agent. Before:

PowerShell
1
2
6 tools: approve_expense_report, create_expense_report, search_expense_reports,
         submit_expense_report, convert_currency, get_expense_report

After:

PowerShell
1
2
5 tools: create_expense_report, search_expense_reports, submit_expense_report,
         convert_currency, get_expense_report

There’s no cache to clear and no extra step. A new run gets a new token, the new claims take effect, and the tool is gone.

Put the assignment back by running Step 6 again.

Notice where that decision is made. The agent filtered nothing. It asked what tools existed and was told five. The same build, the same model and the same prompt behave differently for two people, and neither the client nor the model needs to know why.

The other clients

VS Code Copilot has been our client since Part 2, and Claude got a mention there too. Both of them connect to this server in Part 8, after we deploy it to Azure Container Apps. Neither can use it on localhost, for two different reasons.

Claude never reaches your machine. It connects to your server from Anthropic’s cloud rather than from your laptop, so localhost means nothing to it. That holds for Claude Desktop as well as the website.

VS Code runs locally, but it won’t trust the development certificate. Its MCP client runs on Node, and Node uses OpenSSL. OpenSSL will not accept a certificate that declares it is not a certificate authority, and the ASP.NET Core development certificate declares exactly that. dotnet dev-certs https --trust puts it in the Windows certificate store, which is why our .NET agent connects, but Node doesn’t read the Windows store.

Both of those go away in Part 8, where Container Apps gives the server a public address and a certificate that every client already trusts.

The part worth waiting for is what happens after that. Entra has no way to hand a client an OAuth client ID automatically, so VS Code and Claude both stop and ask you to paste one. That’s the $CLIENT_APP_ID from Step 2. Each of them also returns to a redirect URI of its own, and neither is in the three we registered here, so Part 8 adds them.

Summary

The mechanical part was smaller than I expected. Two app registrations, one file of authentication code, and an attribute on a method.

What took the time was approve_expense_report and its missing approverName. Every tool in Parts 2 through 6 trusts what the model passes it, and that’s fine for a search. It stops being fine as soon as a tool acts on someone’s behalf. The fix isn’t to validate the parameter. It’s to delete it.

The surprise was PKCE. The MCP spec tells clients to refuse an authorization server that doesn’t advertise PKCE. Entra supports PKCE and doesn’t advertise it, so a correct client refuses a working identity provider. Fetching the token ourselves is a fine answer, and I’d expect this to be fixed on one side or the other before long. If you hit it after that, try the SDK’s built in flow first.

Part 8 takes all of this to Azure Container Apps. The app registration we built here gets a second name for the public URL, a managed identity replaces the developer sign-in for the database, and notify_employee arrives to show why that matters. VS Code and Claude connect to the deployed server there.

The source code for this tutorial is available on GitHub.

Follow me on X @TJoudeh and on LinkedIn

References:

  • MCP Authorization specification
  • Secure an MCP server with Microsoft Entra ID
  • Restrictions on identifier URIs of Microsoft Entra applications
  • Add app roles and receive them in the token
  • RFC 9728, OAuth 2.0 Protected Resource Metadata
  • RFC 8707, Resource Indicators for OAuth 2.0
  • VS Code MCP developer guide

Share this:

  • Share on X (Opens in new window) X
  • Share on LinkedIn (Opens in new window) LinkedIn
  • Share on Reddit (Opens in new window) Reddit
  • Share on Facebook (Opens in new window) Facebook
  • Email a link to a friend (Opens in new window) Email

Like this:

Like Loading…

Related Posts

  • Part 10: Observability, Cost Control and MCP Security
  • Part 9: Connecting an MCP Server to Microsoft Foundry Agent Service
  • Part 8: Deploying an MCP Server to Azure Container Apps
  • Part 6: Building an MCP Client and AI Agent in .NET
  • Part 5: Hosting an MCP Server in ASP.NET Core with Streamable HTTP

Filed Under: AI, Azure, MCP Tagged With: .NET 10, ASP.NET Core, Authentication, MCP, Microsoft Entra ID, Model Context Protocol, OAuth 2.1

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About Taiseer

Husband, Father, Consultant @ MSFT, Life Time Learner... Read More…

Buy me a coffeeBuy me a coffee

Recent Posts

  • Part 10: Observability, Cost Control and MCP Security
  • Part 9: Connecting an MCP Server to Microsoft Foundry Agent Service
  • Part 8: Deploying an MCP Server to Azure Container Apps
  • Part 7: Securing an MCP Server with Microsoft Entra ID
  • Part 6: Building an MCP Client and AI Agent in .NET

Blog Archives

Recent Posts

  • Part 10: Observability, Cost Control and MCP Security
  • Part 9: Connecting an MCP Server to Microsoft Foundry Agent Service
  • Part 8: Deploying an MCP Server to Azure Container Apps
  • Part 7: Securing an MCP Server with Microsoft Entra ID
  • Part 6: Building an MCP Client and AI Agent in .NET

Tags

.NET .NET 10 AI Agents AJAX AngularJS API API Versioning ASP.NET ASP.NET 6 Authentication Autherization Server Azure Azure Active Directory B2C Azure AD B2C Azure Container Apps C# Code First Dapr Dependency Injection Entity Framework Foursquare API GitHub Copilot jQuery JSON JSON Web Tokens JWT MCP Microservice Model Context Protocol Ninject OAuth OData Redis Resource Server REST RESTful Single Page Applications SPA Token Authentication Tutorial VS Code Web API Web API 2 Web API Security Web Service

Search

Copyright © 2026 Ā· eleven40 Pro Theme on Genesis Framework Ā· WordPress Ā· Log in

%d