Check 40.13 · AI agent compatibility

Check authentication and authorization

Make sure AI agents only access what the user authorizes: OAuth and scopes, object-level checks, 401 and 403 codes, curl tests and settings by framework.

Priority
Experimental
Difficulty
Advanced
Estimated time
1 to 3 days
Free, no account: your progress is saved in this browser.

Ask an AI to check this point on your site

Opens the assistant with a ready-made question: this check, its goal and your site URL.

For Gemini, Copilot or another assistant, copy the question. The link opens the chosen service directly: nothing goes through this site.

In short

An AI agent acting for a user must be able to authenticate without knowing the user's password, receive only the permissions it needs and never reach another account's data. This check covers three layers: authentication (who is calling), authorization (what they are allowed to do, object by object) and identification of the agent itself. Once it is done, every agent access goes through a revocable, limited-scope delegation, every private resource checks permissions on every request, and 401 and 403 errors are clean and documented. Public pages, for their part, remain accessible without signing in.

Why it matters

Agents access a service in three ways, each with its own risk:

Access mode Example Main risk
Browsing the web interface a browsing agent places an order in your store the user hands their password or session to the agent
Calling an API or an MCP (Model Context Protocol) server a Claude or ChatGPT connector lists a technician's jobs token too broad, valid too long, accepted for another resource
Reading public pages an AI search crawler reads a product page public page blocked by mistake, or private page exposed without checks

The most common flaw is not a missing sign-in but missing object-level checks: the API checks that the caller is signed in, not that job 918 belongs to them. OWASP ranks it first among API risks (API1:2023, Broken Object Level Authorization). A human does not try neighboring IDs; an agent that iterates, or an attacker manipulating it, does so effortlessly.

The MCP specification sets a framework for remote servers: OAuth 2.1, a protected resource metadata document (RFC 9728), a resource parameter that binds each token to the target server (RFC 8707), a 401 response with WWW-Authenticate when there is no valid token, 403 with error="insufficient_scope" when the scope is missing, and a ban on the server accepting or passing through tokens issued for another service. These rules are good practice for any API open to agents.

What it improves

  • Customer data security A compromised or manipulated agent only sees what the user delegated to it.
  • Revocation The user removes an agent's access without changing their password.
  • Agent reliability Explicit 401 and 403 responses let the agent ask for authorization again instead of failing silently.
  • Compliance Access control and data minimization are expectations of the GDPR (General Data Protection Regulation).
  • Visibility Indirect. Public pages accessible without signing in remain readable by search engines and assistants; well-protected private pages do not show up where they should not.

How to check

Prepare two test accounts, A and B, each with its own data, and one token per account. Then, on three or four sensitive routes:

API=https://api.example.com/v1

# 1. No token: 401 expected, never 200 or a 302 to an HTML page
curl -s -o /dev/null -w "%{http_code}\n" $API/interventions/918

# 2. B's token on a resource of A: 403 or 404 expected
curl -s -o /dev/null -w "%{http_code}\n" -H "Authorization: Bearer $TOKEN_B" $API/interventions/918

# 3. Read-only token on a write: 403 expected
curl -s -o /dev/null -w "%{http_code}\n" -X DELETE -H "Authorization: Bearer $TOKEN_A_LECTURE" $API/interventions/918

# 4. Expired or revoked token: 401 expected
curl -s -o /dev/null -w "%{http_code}\n" -H "Authorization: Bearer $TOKEN_REVOQUE" $API/interventions

# 5. Token in the URL: must be rejected
curl -s -o /dev/null -w "%{http_code}\n" "$API/interventions?access_token=$TOKEN_A"

For a remote MCP server, also check discovery:

curl -s -i https://example.com/mcp -X POST -H "Content-Type: application/json" -d '{}' | grep -i "www-authenticate"
curl -s https://example.com/.well-known/oauth-protected-resource | jq

Compliant result: a WWW-Authenticate: Bearer resource_metadata="…" header and a JSON document that lists resource, authorization_servers and scopes_supported.

Finally, check the other direction: your public pages (products, pricing, documentation) must respond 200 without a cookie or sign-in. See make public pages accessible without logging in (opens in a new tab).

How to implement

Before you start

Rules common to all environments:

  1. Never hand a password to an agent. For the API or an MCP server, use OAuth with the authorization code flow and PKCE: the user signs in on your side and grants scopes, and the agent receives a token. For a browsing agent, let the user sign in themselves; consumer agents provide a takeover step for signing in.
  2. Scopes per family of actions: interventions:read, interventions:write, factures:read. No “everything” scope.
  3. Short-lived, revocable tokens: an access token valid for a few minutes to an hour, a revocable refresh token, a “Connected apps” page where the user sees and removes each access.
  4. Object-level checks on every request, on the server side, never in the interface alone: does the resource belong to the token's user?
  5. Tokens bound to the service: check the issuer, the audience and the expiry; reject a token issued for another service.
  6. Standardized errors: 401 with WWW-Authenticate for a missing or invalid token, 403 for insufficient permissions, 404 if revealing that the resource exists is a problem.
  7. A rate limit per token and access logging, to detect an agent enumerating IDs.

Also distinguish the agent's identity from the user's. Some agents sign their HTTP requests (Web Bot Auth, based on RFC 9421): your CDN can recognize them and let them through. This signature says which agent is calling, not which user it represents; it never replaces authorization.

Laravel

Versions Laravel 12 and 13, Passport 13, Sanctum 4.

Declare the scopes with Passport in the boot method of AppServiceProvider:

use Laravel\Passport\Passport;

public function boot(): void
{
    Passport::tokensCan([
        'interventions:read' => 'Read your jobs',
        'interventions:write' => 'Create, modify and cancel your jobs',
    ]);

    Passport::tokensExpireIn(now()->addHour());
    Passport::refreshTokensExpireIn(now()->addDays(30));
}

Require the scope on the routes, in routes/api.php:

use App\Http\Controllers\InterventionsController;
use Laravel\Passport\Http\Middleware\CheckToken;

Route::middleware(['auth:api', 'throttle:api'])->group(function () {
    Route::get('/interventions/{intervention}', [InterventionsController::class, 'show'])
        ->middleware(CheckToken::using('interventions:read'));

    Route::delete('/interventions/{intervention}', [InterventionsController::class, 'destroy'])
        ->middleware(CheckToken::using('interventions:write'));
});

The object-level check goes through a policy, called in each method:

use Illuminate\Support\Facades\Gate;

public function show(Intervention $intervention): InterventionResource
{
    Gate::authorize('view', $intervention);

    return new InterventionResource($intervention);
}
class InterventionPolicy
{
    public function view(User $user, Intervention $intervention): bool
    {
        return $intervention->technicien_id === $user->id;
    }
}

With Sanctum, the equivalent of scopes is called “abilities”: $user->createToken('agent', ['interventions:read']), then $request->user()->tokenCan('interventions:read') or the abilities and ability middlewares. For an MCP server, the Laravel MCP documentation recommends Passport, which provides the OAuth flow that MCP clients expect.

Symfony

Versions Symfony 7 and 8, API Platform 4.

The object-level check goes through a voter, called from the controller or the IsGranted attribute:

use Symfony\Component\Security\Http\Attribute\IsGranted;

#[IsGranted('INTERVENTION_VIEW', subject: 'intervention')]
public function show(Intervention $intervention): JsonResponse

With API Platform, express the rule on the operation:

#[Get(security: "is_granted('ROLE_USER') and object.getTechnicien() == user")]

For OAuth tokens issued by an external server, configure an access_token handler in config/packages/security.yaml and check the issuer, audience and expiry.

Next.js

Versions Next.js 15 and 16 (App Router).

Do not leave authorization to the middleware file alone (called proxy from Next.js 16 onward): a 2025 vulnerability (CVE-2025-29927) made it possible to bypass it on unpatched versions. Check the session and resource ownership in each route handler or server action, as close to the data as possible:

// app/api/interventions/[id]/route.ts
import { NextResponse } from 'next/server';
import { verifierJeton } from '@/lib/auth';
import { db } from '@/lib/db';

export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) {
  const jeton = await verifierJeton(request.headers.get('authorization'), 'interventions:read');

  if (!jeton) {
    return NextResponse.json(
      { title: 'Authentication required', status: 401 },
      { status: 401, headers: { 'WWW-Authenticate': 'Bearer' } },
    );
  }

  const { id } = await params;
  const intervention = await db.intervention.findFirst({
    where: { id: Number(id), technicienId: jeton.userId },
  });

  if (!intervention) {
    return NextResponse.json({ title: 'Not found', status: 404 }, { status: 404 });
  }

  return NextResponse.json(intervention);
}

The verifierJeton function validates the signature, issuer, audience, expiry and scope with your identity provider's library.

WordPress

Versions WordPress 6.4 and later.

  • Application passwords (built in since WordPress 5.6): each user creates a dedicated, revocable password in Users > Profile, in the “Application Passwords” section. This is the minimum for a tool or an agent that calls the REST API: never the main password.
  • A mandatory permission_callback on every custom route. WordPress flags a route that lacks one; for a deliberately public route, write 'permission_callback' => '__return_true' so that the choice is explicit.
  • Object-level checks in the callback: current_user_can( 'edit_post', $request['id'] ) rather than current_user_can( 'edit_posts' ).
  • Minimal roles: create a dedicated user for each integration, with the lowest role that is enough.

Shopify

Versions Shopify admin, November 2026.

Shopify handles customer and staff authentication. Your part: only install apps whose access scopes match their function, review them in Settings > Apps, give named staff accounts with limited permissions, and never share an admin login with an AI service. To sell through assistants, use the channels Shopify provides rather than giving an agent access.

Cloudflare

Versions Cloudflare dashboard, all plans, November 2026.

  • Admin areas: put /admin, /wp-admin or the back office behind Cloudflare Access (Zero Trust), which requires an identity before the request even reaches the server.
  • Rate limiting on the API and sign-in routes: Security > Security rules, a rate limiting rule on the /api/ or /mcp path.
  • Identified agents: in Security > Settings, check how verified bots and signed agents are handled, so as not to block a legitimate agent on your public pages. Letting an agent through the firewall gives it no rights in the application.

AWS

Versions AWS console, November 2026.

On API Gateway, use a JWT authorizer (HTTP API) or Amazon Cognito (REST API) to validate the issuer, audience and scopes before reaching the backend, and attach OAuth scopes to each route. Add AWS WAF with a rate-based rule per IP address or per authorization header from the WAF console. The object-level check stays in the application code: the gateway does not know who owns a resource.

Common mistakes

  • Checking sign-in, not ownership: the signed-in user reads any resource by changing the ID.
  • A single, never-expiring API key shared across all uses, impossible to revoke without breaking everything.
  • A single “everything” scope granted to every agent.
  • Redirecting to an HTML sign-in page with a 302 instead of responding 401 on an API: the agent thinks it succeeded.
  • Tokens in the URL: they end up in logs, browser history and Referer headers.
  • Accepting any token signed by the identity provider, without checking that it was issued for your service.
  • Confusing an identified agent with an authorized user: a verified agent signature grants no rights over an account's data.
  • Putting public pages behind a sign-in out of excessive caution.

Frequently asked questions

Can a user give their password to an AI agent?

They should not have to. For an API or an MCP server, offer OAuth: the user signs in on your side, grants limited and revocable permissions, and the agent receives a token without ever seeing the password. For a browsing agent, the user must be able to enter their credentials themselves. A password handed to an agent can only be revoked by changing it everywhere.

What is the difference between 401 and 403 for an API?

Code 401 means the caller is not authenticated: token missing, expired or invalid. It comes with a WWW-Authenticate header that says how to obtain a token. Code 403 means the caller is identified but does not have the requested permission, for example a missing scope. An agent that receives the right code can ask for authorization again instead of repeating a request doomed to fail.

Should AI agents be blocked from customer accounts?

No, they should be controlled rather than blocked. Customer areas must require authentication for every visitor, human or agent, and check on every request that the resource belongs to the user. An agent acting for a signed-in customer with a limited delegation is legitimate. What must be prevented is access without delegation and access to another account's data.

How should an MCP server handle authentication?

A remote MCP server that gives access to private data follows the authorization part of the specification: OAuth 2.1 with PKCE, a protected resource metadata document, tokens issued specifically for that server and verified on every request, a 401 response with WWW-Authenticate when there is no valid token and 403 when the scope is insufficient. The server must never pass the token it received on to another service.

Updated on

Topic checklist (PDF)

And now?

In the “AI agent compatibility” topic

  1. Use semantic HTML and explicit labels
  2. Identify what each button does
  3. Provide clear error messages
  4. Keep URLs stable
  5. Avoid mandatory complex gestures
  6. Make component states accessible
  7. Display final prices, availability and options
  8. Simplify booking and checkout
  9. Document existing public APIs
  10. Use OpenAPI if relevant
  11. Evaluate MCP based on use cases
  12. Evaluate compatible agentic commerce protocols
  13. Check authentication and authorization
  14. Require confirmation for sensitive actions
  15. Test user journeys with browsing agents
  16. Prevent prompt injection and unauthorized interactions