This prompt acts as a middleware triage step for classifying API requests and user sessions that have already reached an authentication boundary. Its job is to inspect a provided session token or credential payload and produce a structured decision: proceed, escalate for re-authentication, or reject. Platform engineers should use this when they need a clear, auditable auth decision paired with a user-facing message, not just a binary pass/fail from an identity provider. The ideal user is an infrastructure or platform engineer building an AI gateway, an agent harness, or a tool-dispatch layer where downstream models and data stores must not receive requests with missing, expired, or insufficient credentials.
Prompt
Authentication Boundary Triage Prompt

When to Use This Prompt
Understand the job this prompt performs, the required context, and the situations where it should not be applied.
This prompt assumes you already have a credential payload to inspect. It does not perform cryptographic validation, issue tokens, or manage login flows—those responsibilities belong in your identity provider (IdP) and token service. The prompt's value is in interpreting the state of a credential (e.g., expired, missing scopes, anonymous session) and mapping that state to a routing decision and a user-facing message. For example, an expired access token might trigger an escalate decision with a message instructing the client to call the /refresh endpoint, while a valid token with insufficient permissions for a specific tool might trigger a reject decision with a clear scope-denied message. This structured output can then be used by your application's middleware to enforce the decision before any model inference or data access occurs.
Do not use this prompt for initial login flows, credential storage, or cryptographic validation. Those belong in your identity provider, not in an LLM triage layer. Also, avoid using this prompt as a replacement for a policy enforcement point (PEP) that must make sub-millisecond decisions on every request; an LLM call adds latency and cost that is better suited for complex or ambiguous auth states rather than simple token validation. Use this prompt when the auth state requires interpretation—such as distinguishing between an expired token, a token with insufficient scope, and a valid session that needs step-up authentication for a high-risk action. For high-risk domains, always log the prompt's decision alongside the session context for auditability, and consider a human review path for unexpected or low-confidence classifications.
Use Case Fit
Where the Authentication Boundary Triage Prompt works, where it fails, and the operational conditions required for safe deployment.
Good Fit: API Gateway Middleware
Use when: the prompt sits in a request path where every call is inspected before hitting backend services. Guardrail: deploy as a pre-invocation classifier with a hard timeout; if the model does not return a valid auth classification within 500ms, fail closed to an unauthenticated response.
Bad Fit: Real-Time Streaming Sessions
Avoid when: the system maintains long-lived WebSocket or streaming connections where re-authentication mid-session would break the user experience. Guardrail: use token expiry checks at the transport layer instead; reserve this prompt for initial connection handshakes only.
Required Input: Structured Auth Context
Risk: the prompt hallucinates auth requirements when given only a vague user message. Guardrail: always inject a structured auth context object containing auth_status, token_scope, session_age, and required_entitlements; never rely on the model to infer these from free text.
Operational Risk: Over-Escalation Loops
What to watch: the prompt classifies every edge case as requires_reauth, forcing users into infinite login loops. Guardrail: implement a circuit breaker that caps re-authentication requests to 3 per session; after the threshold, escalate to a human support queue with the full classification log.
Operational Risk: Silent Misclassification
What to watch: an expired token is classified as anonymous instead of expired_session, sending users to a generic login page without preserving their in-progress work. Guardrail: add an eval check that verifies the auth_level field matches the injected token state; log every mismatch for prompt iteration.
Bad Fit: Multi-Tenant Authorization Logic
Avoid when: the system needs to resolve complex role-based access across tenants, resource hierarchies, or delegated permissions. Guardrail: this prompt should only classify the authentication boundary; downstream authorization logic must be handled by a dedicated policy engine, not the LLM.
Copy-Ready Prompt Template
Paste this template into your prompt layer to classify authentication boundary violations and generate user-facing re-authentication instructions.
This prompt template is designed to be injected into your authentication middleware layer. It receives a user request and the current session's authentication state, then produces a structured classification that downstream systems can act on. The template uses square-bracket placeholders that your session middleware must populate before invoking the model. Do not hardcode credentials, tokens, or user identifiers directly into the prompt text—inject them through the placeholders at runtime.
textYou are an authentication boundary triage classifier for a production system. Your job is to analyze a user request against the current authentication state and determine whether the request can proceed, requires re-authentication, or must be blocked. ## INPUT User Request: [USER_REQUEST] Authentication State: [AUTH_STATE] - Authenticated: [IS_AUTHENTICATED] - Auth Level: [AUTH_LEVEL] - Session Expiry: [SESSION_EXPIRY] - Required Auth Level for Requested Resource: [REQUIRED_AUTH_LEVEL] ## TASK Classify the request into exactly one of the following categories: - `ALLOW`: The current authentication state is sufficient. No action required. - `REAUTHENTICATE`: Credentials are expired, missing, or insufficient for the requested resource. The user must re-authenticate. - `BLOCK`: The request cannot be satisfied even with re-authentication (e.g., permanently insufficient permissions, banned account, or resource outside user scope). ## OUTPUT_SCHEMA Return a valid JSON object with no additional text: { "classification": "ALLOW" | "REAUTHENTICATE" | "BLOCK", "reason": "Brief technical reason for the classification.", "user_message": "A clear, polite message to show the user. For REAUTHENTICATE, include specific instructions on how to re-authenticate. For BLOCK, explain why access is denied without revealing internal system details.", "required_auth_level": "[REQUIRED_AUTH_LEVEL]" } ## CONSTRAINTS - Never reveal internal session details, token states, or system architecture in the `user_message`. - If `AUTH_LEVEL` is `anonymous` and `REQUIRED_AUTH_LEVEL` is `authenticated`, classify as `REAUTHENTICATE` with a login prompt. - If `SESSION_EXPIRY` is in the past, classify as `REAUTHENTICATE` regardless of `AUTH_LEVEL`. - If `AUTH_LEVEL` is lower than `REQUIRED_AUTH_LEVEL` (e.g., `basic` vs `mfa`), classify as `REAUTHENTICATE` with instructions to escalate. - If the user account is flagged, suspended, or lacks any path to the required level, classify as `BLOCK`. - Do not hallucinate authentication methods the system does not support. ## EXAMPLES Input: User requests `/admin/settings`, AUTH_LEVEL=basic, REQUIRED_AUTH_LEVEL=admin Output: {"classification": "BLOCK", "reason": "Insufficient privilege level", "user_message": "This section requires administrator access. Please contact your admin if you believe this is an error.", "required_auth_level": "admin"} Input: User requests `/profile`, IS_AUTHENTICATED=false, REQUIRED_AUTH_LEVEL=authenticated Output: {"classification": "REAUTHENTICATE", "reason": "Anonymous session", "user_message": "Please log in to view your profile. Click here to sign in.", "required_auth_level": "authenticated"}
Adapt this template by adjusting the AUTH_LEVEL taxonomy to match your system's actual permission model (e.g., anonymous, authenticated, mfa, admin, owner). If your system uses scoped permissions rather than tiered levels, replace the level comparison logic with scope-set intersection checks. The user_message field should be routed to your frontend notification layer, while classification and reason should be logged for audit and observability. Before deploying, run this prompt against a golden dataset of known authentication edge cases—expired tokens, just-expired sessions, privilege escalation attempts, and anonymous access to public endpoints—to verify classification accuracy and refusal tone.
Prompt Variables
Required inputs for the Authentication Boundary Triage Prompt. Each placeholder must be populated before the prompt is assembled and sent to the model. Validation notes describe how to verify the input is well-formed before invocation.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[USER_REQUEST] | The raw user input or API call that triggered the auth boundary check | GET /admin/users without Authorization header | Must be non-empty string. Truncate to 4K characters if longer. Log original for audit trail. |
[AUTH_STATE] | Current authentication context: token status, session validity, credential type | {"authenticated": false, "reason": "missing_token"} | Must be valid JSON object. Required fields: authenticated (boolean), reason (string). Null allowed if auth system is unreachable; flag for human review. |
[REQUIRED_AUTH_LEVEL] | Minimum auth level required for the requested resource or action | role:admin | Must match one of the predefined auth levels in the system policy config. Reject unknown levels before prompt assembly. |
[USER_VISIBLE_ROLES] | Roles the current user holds, if any, for least-privilege comparison | ["viewer"] | Must be a JSON array of strings. Empty array for anonymous users. Validate against known role enum. |
[RESOURCE_SENSITIVITY] | Classification level of the target resource to inform re-auth urgency | high | Must match one of: low, medium, high, critical. Default to high if unset. Controls re-auth instruction tone. |
[REAUTH_INSTRUCTIONS_URL] | Link to platform-specific re-authentication documentation | Must be a valid HTTPS URL. Null allowed for internal-only systems; omit link from output if null. | |
[OUTPUT_SCHEMA] | Expected JSON schema for the classification output | {"auth_decision": "...", "required_level": "...", "user_message": "..."} | Must be a valid JSON Schema object. Validate with Ajv or equivalent before prompt assembly. Reject malformed schemas. |
[CONSTRAINTS] | Additional behavioral constraints: tone, max length, disallowed actions | Do not reveal internal role hierarchy. Keep user message under 200 characters. | Must be a string or null. If present, inject as a separate system-level instruction block. Audit for conflicting constraints. |
Implementation Harness Notes
How to wire the Authentication Boundary Triage Prompt into a production application with validation, retries, logging, and human review.
This prompt is designed to sit at the ingress point of your application, after initial authentication checks have been performed by your identity provider but before any business logic or data access occurs. The harness must inject the current authentication state—including token validity, expiry, scopes, and user tier—into the prompt's [AUTH_STATE] placeholder. This state should be a structured JSON object generated by your auth middleware, not raw token data. The prompt's output is a structured classification that your application router uses to either proceed with the request, escalate for re-authentication, or block access entirely.
Validation and Retries: Parse the model's JSON output and validate it against a strict schema before acting on it. The required_auth_level field must match one of your predefined enum values (e.g., anonymous, authenticated, mfa_required, admin). If validation fails, implement a single retry with a more forceful system instruction that includes the validation error. Do not retry more than once to avoid latency spikes. Logging and Auditing: Log the full input [AUTH_STATE], the model's raw classification, and the final routing decision to an immutable audit log. This is critical for security incident response and for debugging false-positive escalations. Model Choice: A fast, cost-effective model like GPT-4o-mini or Claude 3.5 Haiku is appropriate for this triage task, as it requires instruction-following and structured output more than deep reasoning. Human Review: For high-risk actions (e.g., requests classified as admin but missing MFA), the harness should not automatically escalate the user. Instead, it should flag the request for a human operator review queue and return a generic "request under review" message to the user to avoid information disclosure.
What to Avoid: Do not pass raw user credentials or full tokens into the prompt. The [AUTH_STATE] should be a sanitized summary. Avoid implementing complex retry logic; a single retry on schema validation failure is sufficient. The biggest failure mode in production will be misclassification due to stale or incomplete auth state injected by the middleware. Ensure your auth middleware is the single source of truth and that its output is refreshed on every request before the prompt is assembled.
Expected Output Contract
Defines the exact shape, types, and validation rules for the structured output produced by the Authentication Boundary Triage Prompt. Use this contract to build downstream parsers, logging, and routing logic.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
auth_boundary_classification | enum string | Must be one of: 'authenticated', 'anonymous_fallback', 'credential_expired', 'insufficient_permissions', 'unknown'. Parse check against allowed enum set. | |
required_auth_level | string or null | If classification is 'authenticated' or 'insufficient_permissions', must be a non-empty string matching a known auth level (e.g., 'user', 'admin', 'mfa'). Otherwise, must be null. Schema check with conditional null validation. | |
user_facing_instruction | string | Must be a non-empty string containing clear re-authentication or login steps. If classification is 'anonymous_fallback', must include a path to proceed with limited functionality. Content check for non-empty and contextual relevance. | |
missing_or_expired_credentials | array of strings | Must be a JSON array. If classification is 'credential_expired', must contain at least one string identifying the expired credential (e.g., 'access_token', 'session_cookie'). Otherwise, must be an empty array. Schema and conditional content check. | |
confidence_score | number | Must be a float between 0.0 and 1.0 inclusive. Represents the model's confidence in the classification. Range check and type validation. | |
fallback_action | enum string | Must be one of: 'prompt_for_login', 'redirect_to_idp', 'offer_anonymous_session', 'display_insufficient_permissions_error', 'escalate_to_human'. Parse check against allowed enum set. Must logically correspond to the auth_boundary_classification. | |
reasoning_summary | string or null | If provided, must be a non-empty string briefly explaining the classification logic. If null, no explanation is given. Null allowed. Content check for non-empty if present. |
Common Failure Modes
Authentication boundary triage fails silently, often producing incorrect routing decisions that either lock out legitimate users or grant access to unauthorized ones. These are the most common failure patterns and how to prevent them in production.
Ambiguous Auth State Misclassification
What to watch: The prompt receives conflicting signals—an expired token alongside a valid session cookie—and defaults to 'anonymous' instead of triggering re-authentication. This routes authenticated users into public fallback paths, breaking their experience. Guardrail: Add an explicit tie-breaking rule in the prompt: when multiple auth signals conflict, classify as auth_required with reason: ambiguous_credentials and instruct the system to clear stale tokens before retrying.
Overly Permissive Scope Assignment
What to watch: The model assigns a higher auth level than the evidence supports—granting write or admin scope when only read credentials are present—because it infers intent rather than checking explicit permissions. Guardrail: Constrain the output schema to require an evidence field that cites the specific token claim, role, or permission that justifies the assigned auth level. Reject classifications where the evidence field is empty or speculative.
Re-Auth Instruction Leakage to Anonymous Users
What to watch: The prompt generates re-authentication instructions containing internal endpoints, token formats, or session details that should never be exposed to unauthenticated users. Guardrail: Separate the user_facing_message from the internal_routing_decision in the output schema. Validate that user-facing fields contain no internal URLs, token patterns, or stack traces before returning them.
Expired Token Silent Passthrough
What to watch: The model treats an expired token as valid because the expiration timestamp is in the past but the token structure looks correct. The request proceeds with stale credentials. Guardrail: Add a pre-prompt validation step that checks exp claims before the classification prompt runs. If the token is expired, inject a hard constraint: token_status: expired and force the model to classify as auth_required regardless of other signals.
Insufficient Permission Downgrade Without Explanation
What to watch: The model correctly identifies that the user lacks a required permission but routes to a lower-privilege path without telling the user why their request was downgraded. This creates confusion and support tickets. Guardrail: Require the output to include a permission_gap field that names the missing permission and a user_facing_message that explains what the user can access instead. Test with eval cases where the user expects admin but holds member.
Fallback Path Enumeration via Error Messages
What to watch: The prompt's refusal message reveals the existence of higher-privilege paths—'You need admin access to perform this action'—which attackers can use to map the authorization surface. Guardrail: Design refusal messages to be path-agnostic: 'This action isn't available for your current access level. Contact your administrator if you believe this is an error.' Audit eval outputs for any message that names specific roles, endpoints, or permission tiers.
Evaluation Rubric
Criteria for testing the Authentication Boundary Triage Prompt before production deployment. Each row defines a pass standard, a clear failure signal, and a test method to validate behavior across anonymous, expired, and insufficient-credential scenarios.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Anonymous request detection | Classifies request as auth_required with level anonymous and provides re-authentication instructions | Classifies as authenticated or returns auth level other than anonymous | Run 20 unauthenticated requests with varied phrasing; check classification field equals anonymous |
Expired credential detection | Classifies request as auth_required with level expired and instructs token refresh | Classifies as valid session or returns level insufficient instead of expired | Inject expired JWT tokens into 15 requests; verify level field matches expired and instructions mention refresh |
Insufficient permission detection | Classifies request as auth_required with level insufficient and specifies missing scope | Returns level anonymous or expired when user is authenticated but lacks required permission | Send 15 requests with valid tokens lacking required scopes; check level equals insufficient and missing_scope field is populated |
Valid authenticated request passthrough | Classifies request as authenticated with auth_level set to current user tier | Flags valid request as auth_required or returns null auth_level | Send 20 requests with valid, in-scope tokens; verify classification is authenticated and auth_level is non-null |
Re-authentication instruction clarity | User-facing message includes specific action (login, refresh, request access) and no internal system details | Message contains raw error codes, stack traces, or vague text like 'error occurred' | Review 30 generated messages across all auth boundary types; check for actionable instructions and absence of internal identifiers |
Output schema compliance | Response matches required JSON schema with all required fields present and correctly typed | Missing required fields, wrong types, or extra fields outside schema contract | Validate 50 responses against JSON schema; check field presence, types, and enum values |
Boundary edge case handling | Correctly classifies requests with multiple auth issues (expired token plus insufficient scope) with primary boundary identified | Returns ambiguous classification, picks wrong primary boundary, or omits secondary boundary note | Send 10 requests combining expired tokens and insufficient scopes; verify primary_boundary field is set and secondary_boundary is populated when applicable |
Latency budget compliance | Classification completes within 500ms for 95th percentile of requests | P95 latency exceeds 500ms or timeouts occur on valid inputs | Load test with 100 concurrent requests; measure P95 response time and timeout rate |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Start with the base prompt and a simple JSON schema. Use a single auth_level enum (anonymous, authenticated, elevated, admin) and a boolean requires_reauth flag. Skip token validation and just classify the request state.
codeClassify the auth boundary for this request: [USER_REQUEST] Current auth state: [AUTH_STATE] Return JSON: { "auth_level_required": "anonymous|authenticated|elevated|admin", "requires_reauth": boolean, "reason": "string" }
Watch for
- Missing schema checks on the output
- Overly broad
elevatedclassifications whenauthenticatedwould suffice - No handling of expired-token edge cases

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us