← All articles
Best PracticesNov 29, 202616 min read

Secure MCP Server Authentication: A Step-by-Step Guide

Serdal Tarkan AltunSecurity Research EngineerLinkedIn

Summary

MCP authentication, short for Model Context Protocol authentication, protects a remote MCP server with OAuth. The server publishes protected resource metadata, an authorization server issues short-lived access tokens, and the server accepts only tokens issued for itself. Local stdio servers take credentials from their environment instead, so keep those tokens out of plaintext configuration files.

Quick steps

  1. Inventory your MCP servers and scan local client configuration files for plaintext tokens with the read-only script in Step 1.
  2. On every remote server, answer unauthenticated requests with 401 and a WWW-Authenticate header, and publish OAuth 2.0 Protected Resource Metadata (RFC 9728).
  3. Pick an authorization server, such as your enterprise identity provider (IdP), that advertises PKCE (Proof Key for Code Exchange) with S256 and issues short-lived access tokens.
  4. Validate the signature, issuer, audience, lifetime and scope of every token; reject tokens issued for any other resource.
  5. Publish a minimal scope set and ask for more with insufficient_scope challenges.
  6. Get a separate token for each upstream API; never pass the client's token through.
  7. Keep local server secrets in environment references or an OS secret store, allow only approved servers, and monitor consents and sign-ins.

Applies to: the MCP specification version 2026-07-28, current as of November 2026: remote servers on the Streamable HTTP transport, plus secret handling for local servers on the stdio transport. The Microsoft Entra ID notes cover Microsoft identity platform v2.0 access tokens. The code sample uses Python 3.10 or later with PyJWT 2.10.1 or later. The audit scripts run on Windows PowerShell 5.1 and PowerShell 7.

What is MCP authentication and why does it matter?

MCP authentication is the set of controls that decides which clients and users may call an MCP server's tools, resources and prompts. For HTTP-based transports, the MCP authorization specification builds it on OAuth 2.1. The MCP server is an OAuth resource server, the MCP client is an OAuth client acting for a user, and an authorization server issues the access tokens. Authorization is optional in the protocol, so a server that skips it serves anyone who can reach it.

The glossary pages on AI agent authentication and AI agent authorization explain the concepts; this guide is the implementation. Credentials left in plaintext configuration files are what MITRE ATT&CK tracks as Unsecured Credentials: Credentials In Files (T1552.001). A server that accepts tokens issued for other services turns one stolen OAuth token into access to every service that trusts it. Good MCP server security starts here: treat each MCP client and server as an AI agent identity with an owner and a scope.

Which MCP transports need OAuth?

The specification defines two standard transports, stdio and Streamable HTTP, and its authorization flow applies only to HTTP-based transports.

Transport How it runs How it authenticates Main exposure
stdio The client launches the server as a subprocess and talks to it over standard input and output Should not use the OAuth flow; the server takes credentials from its environment Tokens in config files and environment variables; the server runs with the user's privileges
Streamable HTTP The server runs as an independent process with one HTTP endpoint that accepts POST OAuth 2.1 bearer token in the Authorization header of every request Missing or weak token validation, token passthrough, DNS rebinding of local ports
Custom transport Any channel that carries the JSON-RPC messages Must follow established security practice for that protocol Depends on the channel

The MCP project's local server security guide adds that a client and its stdio servers share one trust domain. The stdio transport is not a sandbox.

What changed in the 2026-07-28 specification?

As of November 2026, the current MCP specification version is 2026-07-28. Compared with version 2025-11-25, these authorization changes matter most:

Change What it means
Dynamic Client Registration is deprecated Client ID Metadata Documents are the recommended path when client and server have no prior relationship; Dynamic Client Registration stays in the specification for at least twelve months
iss in authorization responses Authorization servers should send it (RFC 9207, OAuth 2.0 Authorization Server Issuer Identification), and clients must check a present iss before they redeem the code
Credentials belong to one authorization server Clients key stored client credentials by issuer and register again when the server changes
No protocol sessions The Mcp-Session-Id header is gone; servers mint their own state handles, which must never count as authentication

Before you start

Adding authentication to a server that clients already use is a breaking change. Test in a lab first, with a test authorization server, a test MCP client and a copy of the server.

  • Owners: server owners change code and metadata; identity administrators create app registrations and scopes; endpoint teams run the configuration scan.
  • Inventory: list each MCP server, its transport, its URL or launch command, its owner and the upstream APIs it calls.
  • Authorization server: the MCP authorization tutorial recommends an existing identity provider or authorization server product over writing your own.
  • Impact: unauthenticated clients get 401, and clients that only send static API keys stop working until they support OAuth.
  • Rollback and permissions: keep the previous release deployable, record every registration and scope you create, and confirm you can create app registrations and grant application consent in the IdP.

Step 1: Audit your MCP servers and client configs

Local MCP clients keep server definitions in JSON files, and those definitions can hold API keys or bearer tokens in env, headers or args values. The local server security guide recommends collecting these files across the fleet, because they sit at predictable paths on disk.

The script below reads the configuration files at these documented locations:

Client Files Documented in
Claude Desktop Windows %APPDATA%\Claude\claude_desktop_config.json; macOS ~/Library/Application Support/Claude/claude_desktop_config.json; Linux ~/.config/Claude/claude_desktop_config.json MCP "Connect to local MCP servers" page
Claude Code ~/.claude.json (local and user scope) and .mcp.json in the project root (project scope) Claude Code MCP documentation
Visual Studio Code .vscode/mcp.json in the workspace, .mcp.json at the workspace root, and ~/.copilot/mcp-config.json (or $COPILOT_HOME/mcp-config.json) VS Code MCP configuration reference

VS Code also keeps a user-profile mcp.json, opened with MCP: Open User Configuration. Its reference doesn't give the path on disk, so pass that file with -AdditionalFile, as you would for any other client.

The script is read-only: it reads local files, makes no network call and changes nothing. It never prints, returns or writes a value; a finding names only the client, file, server, JSON key path and reason. It flags literal values under secret-like keys, literal Bearer or Basic credentials, GitHub token prefixes such as ghp_, JSON Web Tokens (JWTs), secrets in arguments and credentials in URL query strings. Run it as the user whose files you check, on Windows PowerShell 5.1 or PowerShell 7; it needs no module and no administrator rights.

#Requires -Version 5.1

<#
.SYNOPSIS
    Read-only scan of local MCP client configuration files for values that look like plaintext tokens.

.DESCRIPTION
    Reads the MCP client configuration files at their documented locations:
    Claude Desktop (claude_desktop_config.json), Claude Code (~/.claude.json and the
    project's .mcp.json) and Visual Studio Code (the workspace .vscode/mcp.json, the
    workspace-root .mcp.json and the Copilot mcp-config.json). Files passed with
    -AdditionalFile are read too.

    Inside every mcpServers or servers object, the script flags string values that look like
    literal credentials: a secret-like key name (token, secret, password, API key,
    authorization, credential) holding a literal value, a literal Bearer or Basic credential,
    a GitHub token prefix, a JWT, a secret passed as a command-line argument, or a
    credential in a URL query string. Values written as references, such as ${VAR},
    ${VAR:-default}, ${env:VAR} or ${input:id}, are not flagged.

    The script never prints, returns or writes a value. A finding holds only the client, the
    file, the server name, the JSON key path and the reason.

.PARAMETER ProjectPath
    Root folder of one project or workspace, for example 'C:\src\example-repo'. The script
    checks its .mcp.json and .vscode\mcp.json files.

.PARAMETER AdditionalFile
    Other MCP configuration files to check, for example the VS Code user-profile mcp.json
    that the MCP: Open User Configuration command opens.

.PARAMETER OutputCsv
    Optional path of a CSV report with the same columns as the console output, for example
    '.\mcp-findings.csv'.

.EXAMPLE
    .\Find-McpPlaintextToken.ps1 -ProjectPath 'C:\src\example-repo'

.EXAMPLE
    pwsh ./Find-McpPlaintextToken.ps1 -ProjectPath ~/src/example-repo -OutputCsv ./mcp-findings.csv

.NOTES
    Read-only. Reads local files only, makes no network call and changes nothing.
    Runs on Windows PowerShell 5.1 and on PowerShell 7 on Windows, macOS and Linux.
    Needs no module and no administrator rights: run it as the user whose files you check.
    The checks are heuristics: review each finding, and treat a clean result as "nothing
    obvious", not as proof that no secret is stored.
#>
[CmdletBinding()]
param(
    [Parameter(Mandatory = $true)]
    [ValidateScript({ Test-Path -LiteralPath $_ -PathType Container })]
    [string]$ProjectPath,

    [string[]]$AdditionalFile = @(),

    [string]$OutputCsv
)

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

# Heuristics. Values are tested after ${...} references are removed.
$secretKeyPattern  = '(?i)(token|secret|passw|api[-_]?key|apikey|authorization|credential|private[-_]?key|access[-_]?key)'
$authValuePattern  = '(?i)\b(bearer|basic)\s+[A-Za-z0-9._~+/=-]{8,}'
$tokenValuePattern = '(ghp_|github_pat_|gho_|ghu_|ghs_|ghr_)[A-Za-z0-9_]{10,}|eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.'
$argSecretPattern  = '(?i)^--?(token|api[-_]?key|secret|password|access[-_]?token)[=:]\S{8,}'
$urlSecretPattern  = '(?i)[?&](token|access_token|api[-_]?key|apikey|key|secret|password)=[^&\s]{8,}'
$referencePattern  = '\$\{[^}]*\}'

$onWindows = ($env:OS -eq 'Windows_NT')
$onMacOS   = [bool](Get-Variable -Name IsMacOS -ValueOnly -ErrorAction SilentlyContinue)

# Documented configuration file locations
$candidates = New-Object System.Collections.Generic.List[object]
if ($onWindows) {
    $candidates.Add([pscustomobject]@{ Client = 'Claude Desktop'; Path = Join-Path $env:APPDATA 'Claude\claude_desktop_config.json' })
}
elseif ($onMacOS) {
    $candidates.Add([pscustomobject]@{ Client = 'Claude Desktop'; Path = Join-Path $HOME 'Library/Application Support/Claude/claude_desktop_config.json' })
}
else {
    $candidates.Add([pscustomobject]@{ Client = 'Claude Desktop'; Path = Join-Path $HOME '.config/Claude/claude_desktop_config.json' })
}
$candidates.Add([pscustomobject]@{ Client = 'Claude Code (local and user scope)'; Path = Join-Path $HOME '.claude.json' })
$candidates.Add([pscustomobject]@{ Client = 'Claude Code or VS Code (workspace root)'; Path = Join-Path $ProjectPath '.mcp.json' })
$candidates.Add([pscustomobject]@{ Client = 'VS Code (workspace)'; Path = Join-Path $ProjectPath '.vscode/mcp.json' })
$copilotHome = if ($env:COPILOT_HOME) { $env:COPILOT_HOME } else { Join-Path $HOME '.copilot' }
$candidates.Add([pscustomobject]@{ Client = 'VS Code Copilot (user)'; Path = Join-Path $copilotHome 'mcp-config.json' })
foreach ($file in $AdditionalFile) {
    $candidates.Add([pscustomobject]@{ Client = 'Additional file'; Path = $file })
}

$findings = New-Object System.Collections.Generic.List[object]

function Add-Finding {
    param([string]$ServerName, [string]$KeyPath, [string]$Reason)
    $findings.Add([pscustomobject]@{
        Client  = $script:currentClient
        File    = $script:currentFile
        Server  = $ServerName
        KeyPath = $KeyPath
        Finding = 'Possible plaintext token'
        Reason  = $Reason
    })
}

function Test-McpValue {
    param([string]$Name, [object]$Value, [string]$KeyPath, [string]$ServerName)
    if (-not ($Value -is [string]) -or [string]::IsNullOrWhiteSpace($Value)) { return }

    $withoutRefs = ($Value -replace $referencePattern, '').Trim()
    $literal = ($withoutRefs -replace '(?i)^(bearer|basic|token)\s+', '').Trim()
    $reasons = New-Object System.Collections.Generic.List[string]

    if ($Name -match $secretKeyPattern -and $literal.Length -ge 8) { $reasons.Add('secret-like key holds a literal value') }
    if ($withoutRefs -match $authValuePattern) { $reasons.Add('literal Bearer or Basic credential') }
    if ($withoutRefs -match $tokenValuePattern) { $reasons.Add('value has a GitHub token prefix or JWT shape') }
    if ($withoutRefs -match $argSecretPattern) { $reasons.Add('secret passed as a command-line argument') }
    if ($withoutRefs -match $urlSecretPattern) { $reasons.Add('credential in a URL query string') }

    if ($reasons.Count -gt 0) {
        Add-Finding -ServerName $ServerName -KeyPath $KeyPath -Reason ($reasons -join '; ')
    }
}

function Search-McpNode {
    param([object]$Node, [string]$Name, [string]$KeyPath, [string]$ServerName, [bool]$IsServerMap)

    if ($Node -is [System.Management.Automation.PSCustomObject]) {
        foreach ($prop in $Node.PSObject.Properties) {
            $childPath = if ($KeyPath) { "$KeyPath.$($prop.Name)" } else { $prop.Name }
            if ($IsServerMap) {
                # Each property of an mcpServers or servers object is one server definition.
                Search-McpNode -Node $prop.Value -Name $prop.Name -KeyPath $childPath -ServerName $prop.Name -IsServerMap $false
            }
            elseif (-not $ServerName -and ($prop.Name -eq 'mcpServers' -or $prop.Name -eq 'servers')) {
                Search-McpNode -Node $prop.Value -Name $prop.Name -KeyPath $childPath -ServerName '' -IsServerMap $true
            }
            else {
                Search-McpNode -Node $prop.Value -Name $prop.Name -KeyPath $childPath -ServerName $ServerName -IsServerMap $false
            }
        }
    }
    elseif ($Node -is [System.Array]) {
        for ($i = 0; $i -lt $Node.Count; $i++) {
            Search-McpNode -Node $Node[$i] -Name $Name -KeyPath "$KeyPath[$i]" -ServerName $ServerName -IsServerMap $false
        }
    }
    elseif ($ServerName) {
        Test-McpValue -Name $Name -Value $Node -KeyPath $KeyPath -ServerName $ServerName
    }
}

foreach ($candidate in $candidates) {
    if (-not (Test-Path -LiteralPath $candidate.Path -PathType Leaf)) {
        Write-Verbose "Not found: $($candidate.Path)"
        continue
    }
    $script:currentClient = $candidate.Client
    $script:currentFile = $candidate.Path
    Write-Verbose "Checking: $($candidate.Path)"
    try {
        $document = Get-Content -LiteralPath $candidate.Path -Raw | ConvertFrom-Json
    }
    catch {
        Add-Finding -ServerName '' -KeyPath '' -Reason 'file could not be parsed as JSON; review it by hand'
        continue
    }
    Search-McpNode -Node $document -Name '' -KeyPath '' -ServerName '' -IsServerMap $false
}

if ($OutputCsv) {
    $findings | Export-Csv -LiteralPath $OutputCsv -NoTypeInformation -Encoding UTF8
}
$findings
.\Find-McpPlaintextToken.ps1 -ProjectPath 'C:\src\example-repo' -OutputCsv '.\mcp-findings.csv' |
    Format-Table Client, Server, KeyPath, Reason -AutoSize

Example output (the values are illustrative):

Client                             Server    KeyPath                                                    Reason
------                             ------    -------                                                    ------
Claude Desktop                     github    mcpServers.github.env.GITHUB_PERSONAL_ACCESS_TOKEN         secret-like key holds a literal value; value has a GitHub token prefix or JWT shape
Claude Code (local and user scope) crm-tools projects.C:/src/example-repo.mcpServers.crm-tools.headers.Authorization secret-like key holds a literal value; literal Bearer or Basic credential
VS Code (workspace)                tickets   servers.tickets.args[2]                                    secret passed as a command-line argument

PowerShell output of the read-only MCP config scan listing client, server, key path and reason, with no token values

The scan names where a token sits, never the token itself

Treat every finding as exposed: rotate the token, then store the new one as Step 7 describes. A token in a checked-in .mcp.json is a hardcoded credential risk for everyone who can read the repository. The checks are heuristics, so a clean result means "nothing obvious", not proof.

Check a remote server's metadata

For each remote server, the second script follows the specification's well-known URI discovery order with GET requests only, first for the protected resource metadata and then for each authorization server's metadata. It is read-only, sends no credential and no MCP request, and needs no module. Run it from an admin workstation that can reach both servers.

#Requires -Version 5.1

<#
.SYNOPSIS
    Read-only check of a remote MCP server's protected resource metadata and its authorization server metadata.

.DESCRIPTION
    Follows the well-known URI discovery order of the MCP authorization specification
    (version 2026-07-28) with GET requests only:

    1. Protected Resource Metadata (RFC 9728) at the path-inserted well-known URI, then at
       the root well-known URI of the MCP server.
    2. For each issuer in authorization_servers, the authorization server metadata at the
       RFC 8414 and OpenID Connect Discovery URIs, in the order the specification lists.

    It reports whether resource matches the MCP server URL, whether the metadata issuer is
    identical to the issuer used to build the URL, whether PKCE with S256 is advertised,
    whether a Dynamic Client Registration endpoint is advertised, whether Client ID Metadata
    Documents and the iss response parameter are supported, and whether offline_access or
    query-string bearer tokens are advertised. It sends no MCP request and no credential.

.PARAMETER McpServerUrl
    The exact MCP endpoint URL that clients connect to, for example
    'https://mcp.example.com/mcp'. Use https; http is accepted only for localhost testing.

.PARAMETER TimeoutSec
    Timeout of each GET request in seconds. Default 15.

.EXAMPLE
    .\Test-McpAuthMetadata.ps1 -McpServerUrl 'https://mcp.example.com/mcp'

.EXAMPLE
    .\Test-McpAuthMetadata.ps1 -McpServerUrl 'https://mcp.example.com/mcp' | Export-Csv .\mcp-metadata.csv -NoTypeInformation

.NOTES
    Read-only. Sends unauthenticated GET requests to public metadata documents and changes
    nothing. Run it from an admin workstation that can reach the MCP server and its
    authorization server. Needs no module and no credentials.
    Runs on Windows PowerShell 5.1 and on PowerShell 7.
#>
[CmdletBinding()]
param(
    [Parameter(Mandatory = $true)]
    [ValidatePattern('^https?://')]
    [string]$McpServerUrl,

    [ValidateRange(1, 120)]
    [int]$TimeoutSec = 15
)

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

$results = New-Object System.Collections.Generic.List[object]

function Add-Result {
    param([string]$Check, [string]$Result, [string]$Detail, [string]$Target)
    $results.Add([pscustomobject]@{ Check = $Check; Result = $Result; Detail = $Detail; Target = $Target })
}

function Get-JsonProperty {
    param([object]$Object, [string]$Name)
    if ($null -eq $Object) { return $null }
    $prop = $Object.PSObject.Properties[$Name]
    if ($null -eq $prop) { return $null }
    return $prop.Value
}

function Get-MetadataDocument {
    param([string[]]$Urls)
    foreach ($url in $Urls) {
        try {
            $doc = Invoke-RestMethod -Method Get -Uri $url -TimeoutSec $TimeoutSec -Headers @{ Accept = 'application/json' }
            if ($doc -is [System.Management.Automation.PSCustomObject]) {
                return [pscustomobject]@{ Url = $url; Document = $doc }
            }
        }
        catch {
            Write-Verbose "No metadata at ${url}: $($_.Exception.Message)"
        }
    }
    return $null
}

$serverUri = [Uri]$McpServerUrl
$isLoopback = $serverUri.Host -in @('localhost', '127.0.0.1', '::1', '[::1]')
if ($serverUri.Scheme -ne 'https' -and -not $isLoopback) {
    Add-Result -Check 'Transport' -Result 'Fail' -Detail 'The MCP server URL is not https' -Target $McpServerUrl
}
if ($McpServerUrl.EndsWith('/') -or $serverUri.Fragment) {
    Add-Result -Check 'Canonical URI' -Result 'Warn' -Detail 'Trailing slash or fragment in the MCP server URL' -Target $McpServerUrl
}

# 1. Protected Resource Metadata: path-inserted URI first, then the root URI
$origin = $serverUri.GetLeftPart([UriPartial]::Authority)
$path = $serverUri.AbsolutePath.TrimEnd('/')
$prmUrls = @()
if ($path) { $prmUrls += "$origin/.well-known/oauth-protected-resource$path" }
$prmUrls += "$origin/.well-known/oauth-protected-resource"

$prm = Get-MetadataDocument -Urls $prmUrls
if ($null -eq $prm) {
    Add-Result -Check 'Protected resource metadata' -Result 'Fail' -Detail 'No metadata at the well-known URIs (the 401 challenge may point elsewhere)' -Target ($prmUrls -join ' ')
    return $results
}
Add-Result -Check 'Protected resource metadata' -Result 'Pass' -Detail 'Metadata found' -Target $prm.Url

$resource = Get-JsonProperty $prm.Document 'resource'
if ($resource -ceq $McpServerUrl) {
    Add-Result -Check 'resource' -Result 'Pass' -Detail 'Identical to the MCP server URL' -Target $prm.Url
}
else {
    Add-Result -Check 'resource' -Result 'Fail' -Detail "resource is '$resource', not the MCP server URL" -Target $prm.Url
}

$scopes = @(Get-JsonProperty $prm.Document 'scopes_supported')
if ($scopes -contains 'offline_access') {
    Add-Result -Check 'scopes_supported' -Result 'Warn' -Detail 'offline_access is listed; the specification says servers should not list it' -Target $prm.Url
}
$bearerMethods = @(Get-JsonProperty $prm.Document 'bearer_methods_supported')
if ($bearerMethods -contains 'query') {
    Add-Result -Check 'bearer_methods_supported' -Result 'Fail' -Detail 'query is listed; MCP forbids access tokens in the query string' -Target $prm.Url
}

$issuers = @(Get-JsonProperty $prm.Document 'authorization_servers' | Where-Object { $_ })
if ($issuers.Count -eq 0) {
    Add-Result -Check 'authorization_servers' -Result 'Fail' -Detail 'No authorization server is listed' -Target $prm.Url
    return $results
}

# 2. Authorization server metadata for each issuer, in the specification's order
foreach ($issuer in $issuers) {
    $issuerUri = [Uri]$issuer
    $asOrigin = $issuerUri.GetLeftPart([UriPartial]::Authority)
    $asPath = $issuerUri.AbsolutePath.TrimEnd('/')
    if ($asPath) {
        $asUrls = @(
            "$asOrigin/.well-known/oauth-authorization-server$asPath",
            "$asOrigin/.well-known/openid-configuration$asPath",
            "$asOrigin$asPath/.well-known/openid-configuration"
        )
    }
    else {
        $asUrls = @(
            "$asOrigin/.well-known/oauth-authorization-server",
            "$asOrigin/.well-known/openid-configuration"
        )
    }

    $as = Get-MetadataDocument -Urls $asUrls
    if ($null -eq $as) {
        Add-Result -Check 'Authorization server metadata' -Result 'Fail' -Detail 'No metadata at the RFC 8414 or OpenID Connect URIs' -Target $issuer
        continue
    }
    $asDoc = $as.Document
    Add-Result -Check 'Authorization server metadata' -Result 'Pass' -Detail 'Metadata found' -Target $as.Url

    if ((Get-JsonProperty $asDoc 'issuer') -ceq $issuer) {
        Add-Result -Check 'issuer' -Result 'Pass' -Detail 'Identical to the issuer in authorization_servers' -Target $as.Url
    }
    else {
        Add-Result -Check 'issuer' -Result 'Fail' -Detail 'Differs from the issuer in authorization_servers; clients must not use this metadata' -Target $as.Url
    }

    $pkce = @(Get-JsonProperty $asDoc 'code_challenge_methods_supported')
    if ($pkce -contains 'S256') {
        Add-Result -Check 'PKCE' -Result 'Pass' -Detail 'S256 is advertised' -Target $as.Url
    }
    else {
        Add-Result -Check 'PKCE' -Result 'Fail' -Detail 'code_challenge_methods_supported is missing (clients refuse to proceed) or lacks S256' -Target $as.Url
    }

    if (Get-JsonProperty $asDoc 'registration_endpoint') {
        Add-Result -Check 'Dynamic Client Registration' -Result 'Warn' -Detail 'registration_endpoint is advertised; restrict it or turn it off if clients do not need it' -Target $as.Url
    }
    else {
        Add-Result -Check 'Dynamic Client Registration' -Result 'Info' -Detail 'No registration_endpoint' -Target $as.Url
    }

    $cimd = (Get-JsonProperty $asDoc 'client_id_metadata_document_supported') -eq $true
    Add-Result -Check 'Client ID Metadata Documents' -Result 'Info' -Detail "client_id_metadata_document_supported = $cimd" -Target $as.Url

    if ((Get-JsonProperty $asDoc 'authorization_response_iss_parameter_supported') -eq $true) {
        Add-Result -Check 'iss in authorization responses' -Result 'Pass' -Detail 'authorization_response_iss_parameter_supported = true' -Target $as.Url
    }
    else {
        Add-Result -Check 'iss in authorization responses' -Result 'Warn' -Detail 'Not advertised (RFC 9207 mix-up protection)' -Target $as.Url
    }

    foreach ($endpointName in @('authorization_endpoint', 'token_endpoint')) {
        $endpoint = Get-JsonProperty $asDoc $endpointName
        if ($endpoint -and -not ([string]$endpoint).StartsWith('https://')) {
            Add-Result -Check $endpointName -Result 'Fail' -Detail 'Not served over https' -Target $as.Url
        }
    }
}

$results
.\Test-McpAuthMetadata.ps1 -McpServerUrl 'https://mcp.example.com/mcp' | Format-Table Check, Result, Detail -AutoSize

Example output (the values are illustrative):

Check                          Result Detail
-----                          ------ ------
Protected resource metadata    Pass   Metadata found
resource                       Pass   Identical to the MCP server URL
Authorization server metadata  Pass   Metadata found
issuer                         Pass   Identical to the issuer in authorization_servers
PKCE                           Pass   S256 is advertised
Dynamic Client Registration    Warn   registration_endpoint is advertised; restrict it or turn it off if clients do not need it
Client ID Metadata Documents   Info   client_id_metadata_document_supported = True
iss in authorization responses Warn   Not advertised (RFC 9207 mix-up protection)

A Fail on issuer, or a PKCE Fail because the field is missing, means compliant clients refuse to start the sign-in. Steps 2 and 3 explain each check.

Step 2: Publish protected resource metadata and a 401 challenge

A remote MCP server must tell clients where to get a token. The specification requires MCP servers to implement OAuth 2.0 Protected Resource Metadata (RFC 9728), with at least one entry in authorization_servers.

Servers advertise the document through the resource_metadata parameter of the WWW-Authenticate header on a 401, or at a well-known URI. For https://mcp.example.com/mcp, that URI is https://mcp.example.com/.well-known/oauth-protected-resource/mcp or the root https://mcp.example.com/.well-known/oauth-protected-resource. Clients use the header first, then the path, then the root.

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource/mcp", scope="mcp:tools"
{
  "resource": "https://mcp.example.com/mcp",
  "authorization_servers": ["https://auth.example.com"],
  "scopes_supported": ["mcp:tools"],
  "bearer_methods_supported": ["header"]
}
Setting Where Recommended value Effect
resource Protected resource metadata The server's canonical URI, such as https://mcp.example.com/mcp: scheme and host in lowercase, no fragment, no trailing slash Clients send this value as the resource parameter; RFC 9728 says clients must not use metadata whose resource doesn't match
authorization_servers Protected resource metadata The issuer identifier of each authorization server you trust for this server Clients discover the authorization server from it; each listed server is independent
scopes_supported Protected resource metadata Only the scopes needed for basic use; leave out offline_access Clients request these when the challenge carries no scope
bearer_methods_supported Protected resource metadata ["header"] MCP requires the token in the Authorization header of every request and forbids it in the query string
scope WWW-Authenticate on 401 and 403 Every scope the current operation needs Clients treat it as authoritative for that request
Origin validation MCP endpoint Allow only the origins you expect; answer 403 to any other The Streamable HTTP transport requires it to stop DNS rebinding
Listening address Local HTTP servers 127.0.0.1, not 0.0.0.0 Keeps the port off the network, but isn't authentication

The Streamable HTTP transport also says servers should authenticate all connections. The local server security guide is blunt about the last row: binding to 127.0.0.1 "is not an authentication boundary".

Step 3: Choose the authorization server and client registration

The authorization server signs users in and issues the tokens your MCP server checks. It must implement OAuth 2.1 and publish OAuth 2.0 Authorization Server Metadata (RFC 8414) or OpenID Connect Discovery metadata. OAuth 2.1 is still an IETF Internet-Draft: the specification cites draft-ietf-oauth-v2-1-13, and as of November 2026 the latest revision is 17.

Setting Where Recommended value Effect
code_challenge_methods_supported Authorization server metadata Includes S256 Clients must use PKCE (Proof Key for Code Exchange, RFC 7636), with S256 when technically capable, and must refuse to proceed if this field is missing
issuer Authorization server metadata Identical to the identifier listed in authorization_servers Clients must not use metadata whose issuer differs
authorization_response_iss_parameter_supported Authorization server metadata true, and send iss in every authorization response Lets clients detect mix-up attacks; the specification expects to make iss mandatory in a future revision
registration_endpoint Authorization server metadata Absent, or restricted to trusted hosts with rate limits Dynamic Client Registration is deprecated; an open endpoint lets anyone register a client
client_id_metadata_document_supported Authorization server metadata true if clients with no prior relationship must connect Enables Client ID Metadata Documents
token_endpoint_auth_methods_supported Authorization server metadata Includes none when public clients connect Many MCP clients have no secret
Access token lifetime Token policy Short A stolen token works until it expires
Refresh tokens for public clients Token policy Rotated Required by the specification
Audience API or resource registration An identifier that belongs to this MCP server only Lets the server reject tokens meant for other services
Redirect URIs Client registration Exact values, localhost or HTTPS only The specification requires exact matching and HTTPS or localhost

Pick a client registration method

A client needs a client ID before it can start the flow. Clients that support every method should use a pre-registered client first, then a Client ID Metadata Document if the authorization server supports it, then Dynamic Client Registration, and finally ask the user.

Method How it works Watch out for
Pre-registration You register the client in the authorization server ahead of time The client must keep the credentials bound to that server's issuer
Client ID Metadata Document The client_id is an HTTPS URL with a path; the authorization server fetches the JSON document there and checks client_id and redirect URIs against it It proves control of a domain, not trustworthiness, and can't stop another local process from claiming a localhost redirect URI
Dynamic Client Registration (RFC 7591) The client registers itself at registration_endpoint Deprecated; turn it off if your clients don't need it

For Client ID Metadata Documents, authorization servers should warn about localhost-only redirect URIs, must show the redirect URI's host name, and may accept only trusted domains. Clients should use and verify the state parameter. They must also send the resource parameter of RFC 8707, Resource Indicators for OAuth 2.0 in both the authorization and the token request, which lets the authorization server restrict the token's audience.

How does an enterprise IdP fit into MCP authentication?

An enterprise identity provider brings single sign-on, conditional access and offboarding to MCP access, in one of two models.

The IdP is the MCP server's authorization server. Microsoft's guide Secure a Model Context Protocol server with Microsoft Entra ID covers Microsoft identity platform v2.0 access tokens only:

  1. Register an application for the MCP server, with its Application ID URI set to the server's canonical endpoint URL: a nonempty path and no trailing slash, such as https://mcp.example.com/mcp.
  2. Expose the delegated scopes clients need, such as mcp.access. Define app roles only for app-only access.
  3. In the protected resource metadata, set resource to the Application ID URI and scopes_supported to the fully qualified scope, such as https://mcp.example.com/mcp/mcp.access.
  4. Set authorization_servers to https://login.microsoftonline.com/<tenant-id>/oauth21/2026-08 for Client ID Metadata Document support. Use organizations in place of the tenant ID to accept users from any organization; the ordinary /v2.0 identifier serves conventional integrations.
  5. Validate tokens as in Step 4, with REQUIRE_AT_JWT_TYP set to False because Entra access tokens carry typ JWT. In these tokens, iss is https://login.microsoftonline.com/<tenant-id>/v2.0, aud is the server application's client ID (a GUID, not the URL), and scp holds the short scope value.

As of November 2026, Client ID Metadata Document support in Microsoft Entra ID is in public preview. The tenant's consent policy decides whether users can add such a client, and each one appears as an agent identity in Entra's inventory, audit logs and sign-in logs. Microsoft recommends pre-registering clients whenever possible.

The IdP decides centrally through an extension. With the Enterprise-Managed Authorization extension, the user signs in to the MCP client through the enterprise IdP. The client exchanges that identity assertion for an Identity Assertion JWT Authorization Grant (ID-JAG) through OAuth 2.0 Token Exchange (RFC 8693). It then trades the ID-JAG for an access token at the MCP server's authorization server with the JWT bearer grant.

The IdP checks group membership, roles and conditional access before it issues the grant, and revoking access there applies across clients. Extensions are opt-in, client support varies, and ID-JAG is still an IETF draft, so confirm support in both your client and your IdP.

Step 4: Validate the access token audience and issuer

MCP servers must validate access tokens as OAuth 2.1 Section 5.2 describes and must confirm that each token was issued for them as the audience. Invalid or expired tokens get 401, and servers must accept no other tokens. For JWT access tokens, RFC 9068 lists the checks: the typ header, an exact iss match, an aud naming this server, a valid signature whose alg isn't none, and an exp in the future.

The Python example below uses PyJWT for those checks and returns a status code and challenge for each request. It is framework-neutral: call check_request() with the Authorization header before you process the MCP message. It needs Python 3.10 or later and pyjwt[crypto] 2.10.1 or later: jwt.decode() accepts the PyJWK key that PyJWKClient returns since 2.9.0, and 2.10.1 fixed partial matching of the iss claim.

"""Validate the access token on each MCP request: signature, issuer, audience, lifetime, scope.

Framework-neutral helper for an MCP server on the Streamable HTTP transport.
Requires Python 3.10 or later and PyJWT 2.10.1 or later with the crypto extra:
    pip install "pyjwt[crypto]>=2.10.1"
Replace the example configuration values with the ones from your authorization server.
"""

import jwt
from jwt.exceptions import PyJWKClientConnectionError, PyJWTError

# One MCP server, one issuer, one audience. Read these from configuration, not from the token.
ISSUER = "https://auth.example.com"  # exact "issuer" value of the authorization server metadata
JWKS_URI = "https://auth.example.com/.well-known/jwks.json"  # "jwks_uri" from the same metadata
EXPECTED_AUDIENCE = "https://mcp.example.com/mcp"  # the value your authorization server puts in "aud" for this server only
ALGORITHMS = ["RS256"]  # fixed list; never derived from the token header
REQUIRED_SCOPE = "mcp:tools"
RESOURCE_METADATA_URL = "https://mcp.example.com/.well-known/oauth-protected-resource/mcp"
REQUIRE_AT_JWT_TYP = True  # RFC 9068 "typ" check; turn off only if your server does not issue RFC 9068 tokens
STRICT_SINGLE_AUDIENCE = True  # PyJWT strict_aud: "aud" must be a single value, not a list

_jwks_client = jwt.PyJWKClient(JWKS_URI, cache_jwk_set=True, lifespan=300, timeout=5)


class TokenRejected(Exception):
    """Missing, malformed, expired, or issued for another resource or issuer: answer 401."""


class AuthorizationServerUnavailable(Exception):
    """The signing keys can't be fetched: answer 503, not 401, so users aren't sent to sign in again."""


def validate_access_token(token: str) -> dict:
    """Return the verified claims, or raise TokenRejected / AuthorizationServerUnavailable."""
    try:
        header = jwt.get_unverified_header(token)
        if REQUIRE_AT_JWT_TYP and str(header.get("typ", "")).lower() not in ("at+jwt", "application/at+jwt"):
            raise TokenRejected("not an RFC 9068 access token")
        signing_key = _jwks_client.get_signing_key_from_jwt(token)
        return jwt.decode(
            token,
            signing_key,
            algorithms=ALGORITHMS,
            issuer=ISSUER,
            audience=EXPECTED_AUDIENCE,
            leeway=30,
            options={"require": ["exp", "iss", "aud"], "strict_aud": STRICT_SINGLE_AUDIENCE},
        )
    except PyJWKClientConnectionError:
        raise AuthorizationServerUnavailable("JWKS endpoint unreachable") from None
    except PyJWTError as exc:
        # Log the exception type only. Never log the token or the Authorization header.
        raise TokenRejected(type(exc).__name__) from None


def token_scopes(claims: dict) -> set[str]:
    """Read "scope" (RFC 9068) or "scp" (used by some identity providers), as a string or a list."""
    value = claims.get("scope", claims.get("scp", ""))
    if isinstance(value, str):
        return set(value.split())
    if isinstance(value, list):
        return {str(item) for item in value}
    return set()


def challenge(scope: str, error: str | None = None) -> str:
    """Build the WWW-Authenticate value for a 401 or 403 response."""
    parts = []
    if error:
        parts.append(f'error="{error}"')
    parts.append(f'scope="{scope}"')
    parts.append(f'resource_metadata="{RESOURCE_METADATA_URL}"')
    return "Bearer " + ", ".join(parts)


def check_request(authorization_header: str | None, needed_scope: str = REQUIRED_SCOPE):
    """Return (status, www_authenticate, claims) for one MCP HTTP request."""
    if not authorization_header or not authorization_header.lower().startswith("bearer "):
        return 401, challenge(needed_scope), None
    token = authorization_header[len("bearer "):].strip()
    try:
        claims = validate_access_token(token)
    except AuthorizationServerUnavailable:
        return 503, None, None
    except TokenRejected:
        return 401, challenge(needed_scope, error="invalid_token"), None
    if needed_scope not in token_scopes(claims):
        return 403, challenge(needed_scope, error="insufficient_scope"), None
    return 200, None, claims
Value Set it to Why
EXPECTED_AUDIENCE The value your authorization server writes in aud for this server only Some products use the resource URL; Microsoft Entra v2 tokens carry the server application's client ID. Never accept a value several servers share
ISSUER One exact issuer string Accept other issuers or tenants only for a server meant to be multi-tenant
ALGORITHMS A fixed list PyJWT warns against deriving it from the token's alg header or other attacker-controlled data
STRICT_SINGLE_AUDIENCE True PyJWT's strict_aud accepts only a single aud value that matches exactly
REQUIRE_AT_JWT_TYP True unless your authorization server uses another typ The MCP authorization tutorial notes that many servers do; never accept an ID token as an access token

Three behaviors matter as much as the checks. An unreachable signing key endpoint returns 503, because a 401 sends users to sign in again without fixing anything. Errors are logged by type, never with the token or the Authorization header. For opaque tokens, call the authorization server's introspection endpoint (RFC 7662) and still check active, aud, scope and exp.

Forestall's research on extracting managed identity tokens from Azure SQL Database shows why the audience, not the URL a token was sent to, decides where a token works.

Step 5: Design scopes for least privilege

Scopes limit what a stolen or misused token can do, so design them per tool or per risk level. The MCP security best practices describe the attack: a token carrying every advertised scope leaks from a log or memory and unlocks unrelated, high-risk tools.

  • Start small. List only the scopes needed for basic functionality in scopes_supported, because clients request all of them when the challenge carries no scope.
  • Step up on demand. When a token lacks a scope, answer 403 with error="insufficient_scope" and every scope the operation needs, in one challenge. Clients should request a new token with the union of old and new scopes.
  • Authorize on the server. A scope in the token isn't enough; your tool code still decides what the user may do. The server must account for scope hierarchies, where a broader scope implies narrower ones.
  • Avoid wildcard scopes such as * or full-access, and version a scope before you change its meaning.
  • Log elevation events: the scope requested and the subset granted, with a correlation ID.
HTTP/1.1 403 Forbidden
WWW-Authenticate: Bearer error="insufficient_scope", scope="files:write", resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource/mcp"

This is least privilege access for agents. An over-permissioned AI agent can start with a server that offered every scope at once.

Step 6: Call upstream APIs without token passthrough

When an MCP server calls other APIs, the client's token isn't a token for those APIs. The security best practices call token passthrough an anti-pattern: the server accepts a token not issued to it and forwards it downstream. The authorization security considerations forbid it. When the server calls an upstream API, it acts as an OAuth client there, with a separate token from the upstream authorization server.

Passthrough bypasses rate limits and validation that depend on the audience, hides which client made a call, and lets one stolen token reach every service that accepts it. Get upstream tokens through the server's own registration with each API, with delegated access limited to what the user approved. For cloud APIs, prefer federation over stored keys, as in replacing GCP service account keys with Workload Identity Federation.

Prevent confused deputy attacks in OAuth proxies

An MCP server that proxies OAuth to a third-party API with one static client ID is exposed to a confused deputy attack. A consent cookie from an earlier sign-in lets an attacker's newly registered client receive the user's authorization code. Such proxies must obtain the user's consent for each dynamically registered client before forwarding:

  • Keep a per-user registry of approved client_id values, and check it before the third-party flow starts.
  • Show your own consent page with the client's name, the third-party scopes and the registered redirect_uri, with cross-site request forgery (CSRF) protection and frame-ancestors or X-Frame-Options: DENY.
  • Give consent cookies the __Host- prefix and the Secure, HttpOnly and SameSite=Lax attributes, sign them and bind them to the client_id.
  • Match redirect_uri exactly, without wildcards.
  • Make state random, single-use and short-lived, such as 10 minutes, and set it only after consent.

The same logic applies to a gateway in front of several MCP servers: it needs its own token for each server behind it, because forwarding the client's token would be passthrough. Servers that keep state should bind each state handle to the user from the verified token and generate handles with a secure random number generator.

Step 7: Keep secrets out of local server configs

Local stdio servers shouldn't use the OAuth flow; the specification says they should retrieve credentials from the environment. That makes the configuration file and the environment the things to protect.

  • Prefer the remote version. A remote server uses the protocol's authorization flow instead of a token in a local file. If a server only wraps a cloud API, run it remotely.
  • Pass secrets per server in each server's env block, not in your shell profile, so a server sees only its own credentials.
  • Reference, don't paste. Claude Code expands ${VAR} and ${VAR:-default} in .mcp.json values. In a remote server's url and headers, it reads its own and cloud provider credential variables as empty, so a shared file can't send them away. In VS Code, input variables for API keys exist only in the mcp.json format of its deprecated Local harness; its portable files take environment-variable references, and its reference warns that a personal configuration file is not a secret store.
  • Use the operating system's secret store where your client can reference it: macOS Keychain, Windows Credential Manager or the freedesktop Secret Service.
  • Scope each token narrowly, such as a fine-grained GitHub token limited to one repository; see the guide to securing GitHub personal access tokens.
  • Isolate third-party servers in a container with no mounts beyond what they need, and block network egress they don't need.
  • Rotate on removal: when you remove a server, rotate every credential it held as part of secret rotation.

Never commit a project-scoped .mcp.json with a literal token, because Claude Code's project scope is designed to be checked into version control. A long-lived secret in that file stays usable until someone rotates it.

Step 8: Strengthen MCP server security with allowlists, gateways and logging

Local MCP servers are software that users install themselves. The local server security guide gives organizations a baseline:

  1. Approved sources: an allowlist of vetted servers with pinned versions, plus criteria for new ones: a known publisher, readable source, provenance metadata and a software bill of materials (SBOM).
  2. Default runtime posture, such as "third-party servers run in containers with no home-directory mounts".
  3. Central deployment where local access isn't needed: one remote instance to patch, audit and control.
  4. Continuous inventory of client configuration files through endpoint management; unlisted servers are shadow AI agents.
  5. An audit trail of which server and tool ran, and when.
  6. A fleet incident plan: find every instance, block its egress, rotate its credentials and push the fixed version.

Clients that install local servers in one click must show the exact command and get approval first. Operators of server-side MCP clients, gateways included, should consider an egress proxy for OAuth discovery that blocks private and link-local addresses, because a malicious server can point metadata URLs at internal services. AI agent security best practices puts these controls into a wider program.

Verify

Check the server from outside after each change. Keep test tokens in environment variables so they stay out of your shell history.

# 1. No token: expect 401 and a WWW-Authenticate header with resource_metadata
curl -si -X POST https://mcp.example.com/mcp \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" | head -n 3

# 2. Foreign Origin header: expect 403
curl -si -X POST https://mcp.example.com/mcp \
  -H "Origin: https://untrusted.example" \
  -H "Content-Type: application/json" | head -n 1

# 3. Valid token issued for another resource: expect 401 with error="invalid_token"
curl -si -X POST https://mcp.example.com/mcp \
  -H "Authorization: Bearer ${OTHER_AUDIENCE_TOKEN}" \
  -H "Content-Type: application/json" | head -n 3

Example output of the first command:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource/mcp", scope="mcp:tools"
Check Expected result
Request without a token 401 with resource_metadata in WWW-Authenticate
Request with a foreign Origin 403
Token issued for another resource or by another issuer 401 with error="invalid_token"
Valid token without the needed scope 403 with error="insufficient_scope" and the missing scope
Valid token with the scope The MCP response
Test-McpAuthMetadata.ps1 No Fail rows
Find-McpPlaintextToken.ps1 on managed machines No findings, or only reviewed exceptions
Upstream API logs Calls arrive with the MCP server's own token, not the client's

Roll back

You can redeploy configuration and code, but exposed secrets and issued tokens don't come back under your control.

Change How to roll back Notes
Token requirement on the server Redeploy the previous release Don't expose an unauthenticated server to a network while you fix it; restrict access at the network layer instead
Protected resource metadata Restore the previous document Run Test-McpAuthMetadata.ps1 again afterwards
Stricter audience or issuer checks Restore the previous configured value Fix the token's aud at the authorization server rather than widening the check
App registration and scopes in the IdP Delete the registration and scopes you created A self-contained JWT that was already issued stays valid at any server that accepts it until it expires
Dynamic Client Registration turned off Turn the registration endpoint back on Restrict it to trusted hosts with rate limits, as in Step 3
Literal tokens removed from configs Don't restore them Treat the old value as exposed: rotate it and reference the new one from the environment
Approved-server allowlist Remove the entry or the policy Users can again install servers outside the list

Monitor and detect

When Microsoft Entra ID is the authorization server, its audit log records the events that grant a client access or give an attacker a foothold in an MCP-related application.

Entra audit activity Why it matters for MCP Related detection rules
Consent to application A user or administrator consented to an MCP client's requested scopes Illicit consent grant detection
Add delegated permission grant Delegated scopes were granted to a client application Same rules; also watch weakened user consent settings
Add service principal credentials A secret or certificate was added to the service principal of the MCP server or a client Credentials added to an application or service principal
Update application An application changed, for example a new redirect URI that receives authorization codes Redirect URI added or changed

If the MCP server or its proxy uses GitHub as the upstream authorization server, watch oauth_application.create and the rules for OAuth app client secrets and ownership changes in GitHub. The token theft and adversary-in-the-middle rules read Entra ID Protection risk detections for users who sign in through Entra. Each rule page includes Sigma rules and, where a mapping exists, Splunk, Microsoft Sentinel and QRadar queries.

The query below lists the client applications used to sign in to one MCP server registered in Entra, from the interactive and non-interactive sign-in tables, whatever the result. Review new client applications and unexpected IP addresses.

// Client applications used to sign in to one MCP server registered in Microsoft Entra ID (all results).
// Needs Microsoft Entra sign-in logs in the SigninLogs and AADNonInteractiveUserSignInLogs tables (diagnostic setting).
let McpServerName = "<display name of the MCP server's app registration>";
union SigninLogs, AADNonInteractiveUserSignInLogs
| where TimeGenerated > ago(14d)
| where ResourceDisplayName == McpServerName
| summarize SignIns = count(), Users = dcount(UserPrincipalName), IPAddresses = make_set(IPAddress, 20), FirstSeen = min(TimeGenerated), LastSeen = max(TimeGenerated) by AppDisplayName, AppId, Type
| order by SignIns desc

On the MCP server, log each token rejection by reason, each scope elevation and each refused Origin, with a correlation ID. Strip Authorization headers, tokens, authorization codes and secrets from every log line.

Troubleshooting

Most of the failures below come from an exact-match rule doing its job: issuer, audience, resource, redirect URI or Origin.

Symptom Cause Fix
Every token gets 401 iss differs from ISSUER, aud differs from the expected audience, or the server clocks disagree Decode a test token and compare both claims character by character; with Entra v2 tokens, expect the client ID GUID in aud
Every token gets 403 with insufficient_scope The scope is in another claim, such as scp, or in an array Read both scope and scp, as token_scopes() does
The client refuses to start the sign-in The authorization server metadata lacks code_challenge_methods_supported, or its issuer doesn't match the identifier in the protected resource metadata Run Test-McpAuthMetadata.ps1 and fix the failing row
The authorization server answers invalid_target The resource value isn't registered exactly as clients send it Register the server URL exactly as clients send it, including the path and any trailing slash
The authorization server rejects a URL client ID It can't fetch the metadata document, or the host isn't on its trusted domain list Allow the client's host, or pre-register the client
Token acquisition fails against Entra ID The MCP endpoint is at the host root or ends in a slash; Microsoft's guide requires an endpoint URL with a nonempty path and no trailing slash as the Application ID URI Host the endpoint at a nonempty path, such as /mcp, without a trailing slash
Users must sign in again during an IdP outage The server answers 401 when it can't fetch signing keys Return 503 for key retrieval failures
403 without insufficient_scope The Origin or Host header was refused Add the expected origin to the allowlist
The scan reports a file it couldn't parse Comments in the file on Windows PowerShell 5.1, or other non-JSON content Review that file by hand, or run the scan on PowerShell 7, which reads JSON with comments

How Forestall helps

When you register an MCP server or a pre-registered MCP client in the Microsoft Entra admin center, Entra creates an application object and a service principal for it. Forestall lists service principals under Unified Identities > Non Human Identities, with their roles, API permissions and a Shadow badge when the object can compromise admin objects through an attack path. Its AZ_ADD_SECRET edge shows which principals can add a client secret to an application or service principal and act as it. The non-human and agent identity compromise use case explains how Forestall finds these identities and what they can reach.

Frequently Asked Questions

How does MCP authentication work?

MCP authentication uses OAuth for remote servers. The client calls the server without a token and gets 401 with a link to the server's protected resource metadata. From it, the client finds the authorization server, signs the user in with the authorization code flow and PKCE, and requests a token for that server with the resource parameter. It then sends the token with every request, and the server validates it.

How do I add authentication to an MCP server?

To add authentication to an MCP server, pick an authorization server, such as your enterprise identity provider, and define a scope for the server. Publish protected resource metadata, answer requests without a valid token with 401 and a WWW-Authenticate header, and validate each token's signature, issuer, audience, lifetime and scope with a well-tested library. Use a separate token for any upstream API, and test with tokens for other audiences.

Does MCP require OAuth?

MCP doesn't require OAuth: the specification makes authorization optional. When a server on an HTTP-based transport supports it, the specification says it should follow the OAuth-based authorization specification: OAuth 2.1, protected resource metadata, resource indicators and PKCE. Servers on the stdio transport shouldn't use that flow and should take credentials from their environment instead. A remote server that skips authorization accepts calls from anyone who can reach its endpoint.

How do I choose an MCP authentication solution?

For MCP authentication, choose an authorization server that publishes RFC 8414 or OpenID Connect metadata including code_challenge_methods_supported, and that accepts the resource parameter or lets you set a unique audience per server. It should also issue short-lived signed tokens or offer introspection, and support public clients. Add Client ID Metadata Documents if unknown clients must connect. An enterprise identity provider adds single sign-on, conditional access and central revocation for employees.

Should a local stdio MCP server use OAuth?

A local stdio MCP server shouldn't use the MCP OAuth flow; the specification says it should take credentials from its environment. Give each server its own narrowly scoped token through the server's environment settings or an operating system secret store, not a literal value in the configuration file. If the server only wraps a remote API, run the remote version, which authenticates with OAuth instead of a stored token.

What is token passthrough in MCP?

Token passthrough is when an MCP server accepts a token that wasn't issued for it and forwards it unchanged to a downstream API. The MCP specification forbids it: servers must accept only tokens issued for themselves and must get a separate token when they call upstream APIs. Passthrough bypasses audience-based controls, hides which client made each call, and lets one stolen token reach every service that trusts it.

References

Share This Article, Secure Your Friends!

See your identity exposure clearly.

Start with a 1-day Proof of Value in your own environment.