π The fast, Pythonic way to build MCP servers and clients.
fix(azure): send prompt=select_account to Entra instead of the consent URL (#5162)
Mayank kumar9768633c1471
diff --git a/docs/integrations/azure.mdx b/docs/integrations/azure.mdxindex c683fbce4..e3d21662a 100644--- a/docs/integrations/azure.mdx+++ b/docs/integrations/azure.mdx@@ -195,6 +195,36 @@ FastMCP automatically prefixes `required_scopes` with your `identifier_uri` (e.gOIDC scopes (`openid`, `profile`, `email`, `offline_access`) are never prefixed and excluded from validation because Azure doesn't include them in access token `scp` claims.</Note>+### Account Selection++By default, `AzureProvider` sends `prompt=select_account` to Azure, so Entra shows an account picker rather than reusing whichever session the browser already holds without asking. Users signed in to several Microsoft accounts, or holding a stale session, can then pick the right one.++Pass `extra_authorize_params` to send different parameters to Azure's authorization endpoint:++```python server.py+from fastmcp import FastMCP+from fastmcp.server.auth.providers.azure import AzureProvider++auth = AzureProvider(+ client_id="your-client-id",+ client_secret="your-client-secret",+ tenant_id="your-tenant-id",+ base_url="http://localhost:8000",+ required_scopes=["read"],+ extra_authorize_params={"domain_hint": "contoso.com"},+)++mcp = FastMCP("My App", auth=auth)+```++A dict you pass replaces the default rather than merging with it. The example above sends `domain_hint` and no `prompt`. To keep the account picker alongside another parameter, name both:++```python+extra_authorize_params={"prompt": "select_account", "domain_hint": "contoso.com"}+```++Passing `{}` sends no extra parameters at all, which leaves Azure to its own default of silent single sign-on.+## Testing### Running the Server@@ -501,6 +531,10 @@ mcp = FastMCP("My App", auth=auth)| Token endpoint | `https://{tenant_name}.b2clogin.com/{tenant_name}.onmicrosoft.com/{policy_name}/oauth2/v2.0/token` || Scope identifier URI | `https://{tenant_name}.onmicrosoft.com/{client_id}` |+<Note>+B2C user flows accept `prompt=login` and reject `prompt=select_account`. `from_b2c()` therefore sends no `prompt` at all, rather than the account-picker default described under [Account Selection](#account-selection). Pass `extra_authorize_params={"prompt": "login"}` to make B2C users re-enter their credentials.+</Note>+### Token Issuer ValidationB2C access tokens carry the **tenant GUID** (not the `.onmicrosoft.com` name)diff --git a/fastmcp_slim/fastmcp/server/auth/providers/azure.py b/fastmcp_slim/fastmcp/server/auth/providers/azure.pyindex b0cf9d360..25b9b741a 100644--- a/fastmcp_slim/fastmcp/server/auth/providers/azure.py+++ b/fastmcp_slim/fastmcp/server/auth/providers/azure.py@@ -120,6 +120,7 @@ class AzureProvider(OAuthProxy):token_expiry_threshold_seconds: int = 0,base_authority: str = "login.microsoftonline.com",token_issuer: str | None = None,+ extra_authorize_params: dict[str, str] | None = None,http_client: httpx2.AsyncClient | None = None,enable_cimd: bool = True,) -> None:@@ -177,6 +178,11 @@ class AzureProvider(OAuthProxy):but the warning is suppressed as an operator acknowledgment thatequivalent protections are enforced externally.SECURITY WARNING: Only set to False for local development or testing environments.+ extra_authorize_params: Parameters to forward to Azure's authorization endpoint.+ Defaults to `{"prompt": "select_account"}` so users can choose which Microsoft+ account to sign in with. An explicit dict replaces that default rather than+ merging with it, so `{"domain_hint": "contoso.com"}` sends the hint without the+ account picker, and `{}` sends neither.http_client: Optional httpx2.AsyncClient for connection pooling in JWKS fetches.When provided, the client is reused for JWT key fetches and the calleris responsible for its lifecycle. When None (default), a fresh client is created per fetch.@@ -256,6 +262,14 @@ class AzureProvider(OAuthProxy):)token_endpoint = f"https://{base_authority}/{tenant_id}/oauth2/v2.0/token"+ # prompt=select_account lets users with multiple or stale Microsoft sessions pick+ # an account instead of Entra silently reusing whichever one the browser holds.+ # An explicit dict replaces this default outright rather than merging over it, so+ # callers can drop the prompt entirely - from_b2c() relies on that, since Azure AD+ # B2C supports prompt=login and rejects select_account.+ if extra_authorize_params is None:+ extra_authorize_params = {"prompt": "select_account"}+# Initialize OAuth proxy with Azure endpoints# Remember there's hooks called, such as _prepare_scopes_for_token_exchange# and _prepare_scopes_for_upstream_refresh@@ -278,6 +292,7 @@ class AzureProvider(OAuthProxy):fallback_refresh_token_expiry_seconds=fallback_refresh_token_expiry_seconds,fastmcp_access_token_expiry_seconds=fastmcp_access_token_expiry_seconds,token_expiry_threshold_seconds=token_expiry_threshold_seconds,+ extra_authorize_params=extra_authorize_params,valid_scopes=parsed_required_scopes,enable_cimd=enable_cimd,)@@ -337,7 +352,9 @@ class AzureProvider(OAuthProxy):`https://{tenant_name}.onmicrosoft.com/{client_id}`.token_issuer: Expected `iss` claim. `None` (default) disablesissuer validation.- **kwargs: Forwarded to `AzureProvider.__init__`.+ **kwargs: Forwarded to `AzureProvider.__init__`. `extra_authorize_params`+ defaults to `{}` here rather than to the account-picker prompt, because+ B2C user flows only support `prompt=login`."""if ".onmicrosoft.com" in tenant_name:raise ValueError(@@ -356,6 +373,12 @@ class AzureProvider(OAuthProxy):tenant_path = f"{tenant_name}.onmicrosoft.com/{policy_name}"uri = identifier_uri or f"https://{tenant_name}.onmicrosoft.com/{client_id}"+ # B2C user flows reject prompt=select_account (login is the only value they+ # support), so opt out of the account-picker default the standard constructor+ # applies. Callers can still pass extra_authorize_params to set their own.+ if kwargs.get("extra_authorize_params") is None:+ kwargs["extra_authorize_params"] = {}+provider = cls(client_id=client_id,client_secret=client_secret,@@ -388,7 +411,8 @@ class AzureProvider(OAuthProxy):params: Authorization parameters from the clientReturns:- Authorization URL to redirect the user to Azure AD+ URL to redirect the user to: the local consent screen when consent is+ enabled, otherwise the Azure AD authorization URL."""# Clear the resource parameter that Azure AD v2.0 doesn't support# This parameter comes from RFC 8707 (OAuth 2.0 Resource Indicators)@@ -405,9 +429,7 @@ class AzureProvider(OAuthProxy):)# Don't modify the scopes in params - they stay unprefixed for MCP clients# We'll prefix them when building the Azure authorization URL (in _build_upstream_authorize_url)- auth_url = await super().authorize(client, params_to_use)- separator = "&" if "?" in auth_url else "?"- return f"{auth_url}{separator}prompt=select_account"+ return await super().authorize(client, params_to_use)def _prefix_scopes_for_azure(self, scopes: list[str]) -> list[str]:"""Prefix unprefixed custom API scopes with identifier_uri for Azure.diff --git a/tests/server/auth/providers/test_azure.py b/tests/server/auth/providers/test_azure.pyindex 704af3ab4..2d6d747ff 100644--- a/tests/server/auth/providers/test_azure.py+++ b/tests/server/auth/providers/test_azure.py@@ -1,6 +1,7 @@"""Tests for Azure (Microsoft Entra) OAuth provider."""import time+from typing import Any, Literalfrom unittest.mock import AsyncMock, patchfrom urllib.parse import parse_qs, urlparse@@ -850,6 +851,174 @@ class TestAzureProvider:assert result.count("api://my-api/read") == 1+class TestAzureProviderPrompt:+ """Tests that prompt reaches Azure rather than FastMCP's own consent page."""++ @pytest.fixture+ def client(self) -> OAuthClientInformationFull:+ return OAuthClientInformationFull(+ client_id="dummy",+ client_secret="secret",+ redirect_uris=[AnyUrl("http://localhost:12345/callback")],+ )++ @pytest.fixture+ def params(self) -> AuthorizationParams:+ return AuthorizationParams(+ redirect_uri=AnyUrl("http://localhost:12345/callback"),+ redirect_uri_provided_explicitly=True,+ scopes=["read"],+ state="abc",+ code_challenge="xyz",+ )++ @pytest.mark.parametrize("consent", [True, "remember"])+ async def test_prompt_reaches_azure_not_the_consent_url(+ self,+ memory_storage: MemoryStore,+ client: OAuthClientInformationFull,+ params: AuthorizationParams,+ consent: bool | Literal["remember"],+ ):+ """With the consent screen in the loop, prompt belongs on the Azure URL."""+ provider = AzureProvider(+ client_id="test_client",+ client_secret="test_secret",+ tenant_id="common",+ required_scopes=["read"],+ base_url="https://srv.example",+ jwt_signing_key="test-secret",+ client_storage=memory_storage,+ require_authorization_consent=consent,+ )+ await provider.register_client(client)++ url = await provider.authorize(client, params)++ # authorize() returns the local consent page, which must stay clean+ assert url.startswith("https://srv.example/consent?")+ assert "prompt" not in url++ txn_id = parse_qs(urlparse(url).query)["txn_id"][0]+ transaction = await provider._transaction_store.get(key=txn_id)+ assert transaction is not None++ upstream_url = provider._build_upstream_authorize_url(+ txn_id, transaction.model_dump()+ )+ assert upstream_url.startswith("https://login.microsoftonline.com/")+ assert "prompt=select_account" in upstream_url++ async def test_prompt_sent_once_when_consent_disabled(+ self,+ memory_storage: MemoryStore,+ client: OAuthClientInformationFull,+ params: AuthorizationParams,+ ):+ """Without the consent screen, authorize() returns the Azure URL directly."""+ provider = AzureProvider(+ client_id="test_client",+ client_secret="test_secret",+ tenant_id="common",+ required_scopes=["read"],+ base_url="https://srv.example",+ jwt_signing_key="test-secret",+ client_storage=memory_storage,+ require_authorization_consent=False,+ )+ await provider.register_client(client)++ url = await provider.authorize(client, params)++ assert url.startswith("https://login.microsoftonline.com/")+ assert "prompt=select_account" in url+ assert url.count("prompt=") == 1++ async def test_extra_authorize_params_override_default_prompt(+ self,+ memory_storage: MemoryStore,+ client: OAuthClientInformationFull,+ params: AuthorizationParams,+ ):+ """Caller-supplied params win over the select_account default."""+ provider = AzureProvider(+ client_id="test_client",+ client_secret="test_secret",+ tenant_id="common",+ required_scopes=["read"],+ base_url="https://srv.example",+ jwt_signing_key="test-secret",+ client_storage=memory_storage,+ require_authorization_consent=False,+ extra_authorize_params={+ "prompt": "login",+ "domain_hint": "contoso.com",+ },+ )+ await provider.register_client(client)++ url = await provider.authorize(client, params)++ assert "prompt=login" in url+ assert "domain_hint=contoso.com" in url+ assert "select_account" not in url++ @pytest.mark.parametrize(+ "extra_authorize_params", [{}, {"extra_authorize_params": None}]+ )+ async def test_b2c_does_not_send_select_account(+ self,+ memory_storage: MemoryStore,+ client: OAuthClientInformationFull,+ params: AuthorizationParams,+ extra_authorize_params: dict[str, Any],+ ):+ """B2C user flows only support prompt=login, so send no prompt by default."""+ provider = AzureProvider.from_b2c(+ tenant_name="mytenant",+ policy_name="B2C_1_susi",+ client_id="test_client",+ client_secret="test_secret",+ required_scopes=["read"],+ base_url="https://srv.example",+ jwt_signing_key="test-secret",+ client_storage=memory_storage,+ require_authorization_consent=False,+ **extra_authorize_params,+ )+ await provider.register_client(client)++ url = await provider.authorize(client, params)++ assert url.startswith("https://mytenant.b2clogin.com/")+ assert "prompt=" not in url++ async def test_b2c_accepts_an_explicit_prompt(+ self,+ memory_storage: MemoryStore,+ client: OAuthClientInformationFull,+ params: AuthorizationParams,+ ):+ """The B2C opt-out is a default, not a restriction."""+ provider = AzureProvider.from_b2c(+ tenant_name="mytenant",+ policy_name="B2C_1_susi",+ client_id="test_client",+ client_secret="test_secret",+ required_scopes=["read"],+ base_url="https://srv.example",+ jwt_signing_key="test-secret",+ client_storage=memory_storage,+ require_authorization_consent=False,+ extra_authorize_params={"prompt": "login"},+ )+ await provider.register_client(client)++ url = await provider.authorize(client, params)++ assert "prompt=login" in url++class TestAzureProviderTokenIssuer:"""Tests for the token_issuer parameter on AzureProvider."""