---
name: dev-proxy
description: Sets up Microsoft Dev Proxy v3 for a React + TypeScript SPA with MSAL authentication.
When invoked, writes devproxyrc.json, entra-mocks.json, and api-mocks.json, and wires MSAL (@azure/msal-browser + @azure/msal-react) into the application entry point and auth component. Use on any mention of "dev proxy", "devproxy", "mock auth", "mock Entra", "MSAL proxy", or any request to intercept Entra/Azure AD auth locally without a real tenant. Also provides commands for starting and stopping Dev Proxy from the CLI.
---
# Dev Proxy v3 + MSAL Setup Skill
When this skill is invoked, perform every numbered step below in order. Infer configuration values from context (CLAUDE.md, vite.config.ts, existing authConfig.ts, package.json) wherever possible. Ask the user only for information you cannot determine yourself. Also watch for the user to start and stop Dev Proxy from the CLI, and provide instructions as needed.
---
## Step 0 — Locate the web app
Identify the React/TypeScript project root: the directory that contains (or will contain)`package.json` and the Dev Proxy files. If there are multiple web projects in the solution,ask the user which one to configure.
---
## Step 1 — Collect configuration values
| Variable | Where to look | Default / fallback |
|---|---|---|
| `APP_URL` | `vite.config.ts` server.port, existing authConfig.ts redirectUri | Ask user |
| `API_URL` | Vite proxy config, CLAUDE.md architecture section | Ask user |
| `TENANT_ID` | Existing authConfig.ts | `aaaabbbb-cccc-dddd-eeee-ffffaaaabbbb` |
| `CLIENT_ID` | Existing authConfig.ts | `11112222-3333-4444-5555-666677778888` |
The default TENANT_ID and CLIENT_ID are dummy GUIDs — no real Azure tenant or app registration is required. Dev Proxy intercepts all calls to login.microsoftonline.com.
---
## Step 2 — Install MSAL packages
If `@azure/msal-browser` and `@azure/msal-react` are not already in `package.json`:
```powershell
npm install @azure/msal-browser @azure/msal-react
```
---
## Step 3 — Write devproxyrc.json
Write to the web app root, substituting `API_URL` and `TENANT_ID`/`CLIENT_ID`:
```json
{
  "$schema": "https://raw.githubusercontent.com/dotnet/dev-proxy/main/schemas/v3.0.0/rc.schema.json",
  "urlsToWatch": [
    "https://login.microsoftonline.com/*",
    "API_URL/*"
  ],
  "plugins": [
    {
      "name": "EntraMockResponsePlugin",
      "enabled": true,
      "pluginPath": "~appFolder/plugins/DevProxy.Plugins.dll",
      "configSection": "entraMocksPlugin"
    },
    {
      "name": "MockResponsePlugin",
      "enabled": true,
      "pluginPath": "~appFolder/plugins/DevProxy.Plugins.dll",
      "configSection": "apiMocksPlugin"
    },
    {
      "name": "AuthPlugin",
      "enabled": true,
      "pluginPath": "~appFolder/plugins/DevProxy.Plugins.dll",
      "configSection": "auth"
    }
  ],
  "entraMocksPlugin": {
    "$schema": "https://raw.githubusercontent.com/dotnet/dev-proxy/main/schemas/v3.0.0/mockresponseplugin.schema.json",
    "mocksFile": "entra-mocks.json"
  },
  "apiMocksPlugin": {
    "$schema": "https://raw.githubusercontent.com/dotnet/dev-proxy/main/schemas/v3.0.0/mockresponseplugin.schema.json",
    "mocksFile": "api-mocks.json",
    "blockUnmockedRequests": false
  },
  "auth": {
    "$schema": "https://raw.githubusercontent.com/dotnet/dev-proxy/main/schemas/v3.0.0/authplugin.schema.json",
    "type": "oauth2",
    "oauth2": {
      "metadataUrl": "https://login.microsoftonline.com/TENANT_ID/v2.0/.well-known/openid-configuration",
      "allowedAudiences": ["api://CLIENT_ID"],
      "allowedApplications": ["CLIENT_ID"],
      "validateSigningKey": false,
      "validateLifetime": false
    }
  }
}
```
---
## Step 4 — Write entra-mocks.json
Write to the web app root, substituting `APP_URL` and `CLIENT_ID`.
### Four rules that the Dev Proxy documentation gets wrong
1. **Location header uses `#` not `?`.**
MSAL browser v3 sends `response_mode=fragment` and reads the auth code from `window.location.hash`. A `?` redirect puts the code in the query string where MSAL never looks — `handleRedirectPromise()` fires and exits without processing anything.
2. **Token URL pattern must end in `*`.**
MSAL appends `?client-request-id=...` to the token endpoint URL. Without a trailing wildcard (`oauth2/v2.0/token*`) the pattern never matches, EntraMockResponsePlugin skips it, and AuthPlugin returns 401.
3. **Token response must include `Access-Control-Allow-Origin`.**
The token exchange is a `fetch()` with `mode: cors`. Without this header the browser blocks the response even though Dev Proxy returned 200.
4. **Use a fixed nonce, not the `@dynamic.` prefix.**
The `@dynamic.` nonce substitution in id_token payloads is unreliable. Instead, embed `"nonce":"mocked-nonce"` directly in the id_token and pass the same fixed nonce in the `loginRedirect` call (Step 8). `state=@dynamic` in the Location header remains required and does work correctly.
### Pre-computed tokens for the default dummy IDs
If using `TENANT_ID = aaaabbbb-cccc-dddd-eeee-ffffaaaabbbb` and
`CLIENT_ID = 11112222-3333-4444-5555-666677778888`, use the tokens below verbatim.
If using different IDs, run the PowerShell at the end of this step to regenerate them.
```json
{
  "$schema": "https://raw.githubusercontent.com/dotnet/dev-proxy/main/schemas/v3.0.0/mockresponseplugin.mocksfile.schema.json",
  "mocks": [
    {
      "request": {
        "url": "https://login.microsoftonline.com/*/oauth2/v2.0/authorize*",
        "method": "GET"
      },
      "response": {
        "statusCode": 302,
        "headers": [
          {
            "name": "Location",
            "value": "APP_URL/#code=MOCK_AUTH_CODE&state=@dynamic&session_state=MOCK_SESSION"
          }
        ],
        "body": ""
      }
    },
    {
      "request": {
        "url": "https://login.microsoftonline.com/*/oauth2/v2.0/token*",
        "method": "POST"
      },
      "response": {
        "statusCode": 200,
        "headers": [
          { "name": "Content-Type", "value": "application/json; charset=utf-8" },
          { "name": "Access-Control-Allow-Origin", "value": "APP_URL" }
        ],
        "body": {
          "token_type": "Bearer",
          "scope": "api://CLIENT_ID/user_impersonation",
          "expires_in": 3599,
          "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ2ZXIiOiIyLjAiLCJpc3MiOiJodHRwczovL2xvZ2luLm1pY3Jvc29mdG9ubGluZS5jb20vYWFhYWJiYmItY2NjYy1kZGRkLWVlZWUtZmZmZmFhYWFiYmJiL3YyLjAiLCJzdWIiOiJBQUFBQUFBQUFBQUFBQUFBQUFBQUFKUjBvSUIzR1BRRTFPYzBHaHlKOUEiLCJhdWQiOiJhcGk6Ly8xMTExMjIyMi0zMzMzLTQ0NDQtNTU1NS02NjY2Nzc3Nzg4ODgiLCJzY3AiOiJ1c2VyX2ltc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ituting your actual TENANT_ID and CLIENT_ID, then replace the `access_token` and `id_token` values in the file above:
```powershell
$TENANT_ID = 'YOUR_TENANT_ID'
$CLIENT_ID = 'YOUR_CLIENT_ID'
$accessPayload = "{`"ver`":`"2.0`",`"iss`":`"https://login.microsoftonline.com/$TENANT_ID/v2.0`",`"sub`":`"AAAAAAAAAAAAAAAAAAAAAJRoIB3GPQE1Oc0GhyJ9A`",`"aud`":`"api://$CLIENT_ID`",`"scp`":`"user_impersonation`",`"appid`":`"$CLIENT_ID`",`"azp`":`"$CLIENT_ID`",`"exp`":9999999999,`"iat`":1700000000,`"nbf`":1700000000,`"oid`":`"$TENANT_ID`",`"tid`":`"$TENANT_ID`",`"aio`":`"mock_aio`"}"
$idPayload = "{`"ver`":`"2.0`",`"iss`":`"https://login.microsoftonline.com/$TENANT_ID/v2.0`",`"sub`":`"AAAAAAAAAAAAAAAAAAAAAJRoIB3GPQE1Oc0GhyJ9A`",`"aud`":`"$CLIENT_ID`",`"exp`":9999999999,`"iat`":1700000000,`"nbf`":1700000000,`"name`":`"MockUser`",`"preferred_username`":`"mockuser@example.com`",`"oid`":`"$TENANT_ID`",`"tid`":`"$TENANT_ID`",`"nonce`":`"mocked-nonce`",`"aio`":`"mock_aio`"}"
function ConvertTo-Base64Url($json) {
  $bytes = [System.Text.Encoding]::UTF8.GetBytes($json)
  [System.Convert]::ToBase64String($bytes).Replace('+','-').Replace('/','_').TrimEnd('=')
}
$header = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9"
Write-Output "access_token: $header.$(ConvertTo-Base64Url $accessPayload).MOCK_SIG"
Write-Output "id_token: $header.$(ConvertTo-Base64Url $idPayload).MOCK_SIG"
```
---
## Step 5 — Write api-mocks.json
Write this empty template to the web app root:
```json
{
  "$schema": "https://raw.githubusercontent.com/dotnet/dev-proxy/main/schemas/v3.0.0/mockresponseplugin.mocksfile.schema.json",
  "mocks": []
}
```
---
## Step 6 — Write src/authConfig.ts
Write this file to the web app `src/` directory, substituting TENANT_ID, CLIENT_ID, and APP_URL.
If the file already exists with different IDs, preserve the existing IDs.
```typescript
import { Configuration, LogLevel } from '@azure/msal-browser';
const TENANT_ID = 'TENANT_ID';
const CLIENT_ID = 'CLIENT_ID';
export const msalConfig: Configuration = {
  auth: {
    clientId: CLIENT_ID,
    authority: `https://login.microsoftonline.com/${TENANT_ID}`,
    redirectUri: 'APP_URL',
    postLogoutRedirectUri: 'APP_URL',
  },
  system: {
    loggerOptions: {
      loggerCallback: (_level, message) => console.log('[MSAL]', message),
      logLevel: LogLevel.Warning,
    },
  },
};
export const loginRequest = {
  scopes: [`api://${CLIENT_ID}/user_impersonation`],
};
```
---
## Step 7 — Update the application entry point (main.tsx / index.tsx)
Read the existing entry point. Apply these changes:
1. Import `PublicClientApplication` from `@azure/msal-browser`, `MsalProvider` from `@azure/msal-react`, and `msalConfig` from `./authConfig`.
2. Create the MSAL instance **outside** React's render cycle (module scope).
3. Move `createRoot(...).render(...)` **inside** `msalInstance.initialize().then(...)`.
Without this, `loginRedirect()` throws `uninitializedPublicClientApplication` silently before the try/catch in the sign-in handler can catch it — the button appears to do nothing.
4. Wrap the root component in `<MsalProvider instance={msalInstance}>`.
```tsx
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { PublicClientApplication } from '@azure/msal-browser';
import { MsalProvider } from '@azure/msal-react';
import { msalConfig } from './authConfig';
import App from './App';
const msalInstance = new PublicClientApplication(msalConfig);
msalInstance.addEventCallback(event => {
  if (event.error) console.error('[MSAL]', event.eventType, event.error);
  else console.log('[MSAL event]', event.eventType, event.payload ?? '');
});
msalInstance.initialize().then(() => {
  createRoot(document.getElementById('root')!).render(
    <StrictMode>
      <MsalProvider instance={msalInstance}>
        <App />
      </MsalProvider>
    </StrictMode>
  );
});
```
---
## Step 8 — Wire the fixed nonce into the login call
Find the component that calls `instance.loginRedirect()`. Add `nonce: 'mocked-nonce'` to the request object. This must match the `"nonce":"mocked-nonce"` claim embedded in the id_token in entra-mocks.json. Without it, MSAL generates a random nonce, stores it in sessionStorage, and then rejects the returned id_token because the nonces don't match — the auth flow silently fails after the redirect.
```tsx
await instance.loginRedirect({ ...loginRequest, nonce: 'mocked-nonce' });
```
Do **not** add `nonce` to `loginRequest` itself. `acquireTokenSilent` spreads `loginRequest`
too, and a stale nonce there causes silent refresh to fail.
---
## Step 9 — Write .env.local
Write this to the web app root. The cert file must be exported once per machine with `devproxy certificate get --output devproxy-ca.crt`. Without it, Node/Vite rejects Dev Proxy's TLS interception with `ERR_CERT_AUTHORITY_INVALID`.
```
NODE_EXTRA_CA_CERTS=./devproxy-ca.crt
```
---
## Step 10 — Initialize devproxy with its certificate
```powershell
devproxy certificate get --output devproxy-ca.crt
```
## Step 11 — Give the user run instructions
After writing all files:
```
To start the mock auth flow:
1. Start Dev Proxy (from the web app directory):
devproxy
Accept the CA trust prompt on first run.
2. Start the dev server in a second terminal:
npm run dev
3. Open APP_URL — sign in with the button.
The page briefly redirects and returns; that is the mock auth flow working.
Note: if you ed entra-mocks.json or api-mocks.json then restart Dev Proxy (Ctrl+C, then devproxy)— Dev Proxy does not hot-reload those files.
```
### Start
```powershell
# From the folder containing devproxyrc.json (auto-loaded)
devproxy
# Point at a specific config file
devproxy --config-file ./config/devproxyrc.json
# Don't touch the system proxy (useful in CI or when another proxy is active)
devproxy --as-system-proxy false
```
---
## Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
| Button click does nothing; console shows `msal:handleRedirectStart` → `msal:handleRedirectEnd` with no token events in between | Location header uses `?` — MSAL looks only at `window.location.hash` | Change `?code=` to `#code=` in the authorize mock Location header |
| `msal:loginFailure 401 Unauthorized`; Dev Proxy shows `AuthPlugin: 401 Authorization header not found` | Token URL mock not matched (query params present, no trailing wildcard) | Ensure token URL pattern ends in `*`: `oauth2/v2.0/token*` |
| CORS error on token POST despite Dev Proxy returning 200 | Token mock response missing `Access-Control-Allow-Origin` | Add `{"name":"Access-Control-Allow-Origin","value":"APP_URL"}` to the token mock response headers |
| `msal:loginFailure` nonce mismatch | Random nonce stored by MSAL doesn't match static nonce in id_token | Pass `nonce: 'mocked-nonce'` in the `loginRedirect` call; ensure id_token payload contains `"nonce":"mocked-nonce"` |
| Sign-in button does nothing, no MSAL events in console | `render()` called before `initialize()` completes | Move render inside `msalInstance.initialize().then(...)` |
| Mock changes not picked up | Dev Proxy reads config files at startup only | Restart Dev Proxy after editing any mock file |
| `ERR_CERT_AUTHORITY_INVALID` in browser | Dev Proxy CA not trusted | Accept the cert prompt on startup, or run `devproxy certificate install` |
| `ERR_CERT_AUTHORITY_INVALID` in Vite/Node | Node ignores the Windows certificate store | Set `NODE_EXTRA_CA_CERTS=./devproxy-ca.crt` in `.env.local` |
## Support starting and stopping Dev Proxy from the CLI
### Start
```powershell
# From the folder containing devproxyrc.json (auto-loaded)
devproxy
# Point at a specific config file
devproxy --config-file ./config/devproxyrc.json
# Don't touch the system proxy (useful in CI or when another proxy is active)
devproxy --as-system-proxy false
```
Don't display the start instructions again if the user has already run the command once in this terminal session.
### Stop
From the running terminal: **Ctrl+C**
From a second terminal:
```powershell
devproxy stop # Stop all instances
devproxy stop --pid 12345 # Stop a specific instance
devproxy stop --force # Force-terminate if graceful stop fails
```
Don't display the start instructions again if the user has already run the command once in this terminal session.
