API Security
.
12
Mins Read

The Principle of Least Privilege for APIs, Explained

Most API consumers can do far more than they ever will. This guide explains the principle of least privilege for APIs, why over-permissioned keys and tokens cause real breaches, and how to apply it to scopes, data and time, then measure it, with tested code and a checklist.

Dhayalan Subramanian
Associate Director - Product Growth at DigitalAPI
.
19 November 2026
In this blog
Share blog
TL;DR:

What is the principle of least privilege?

The principle of least privilege (PoLP) means every user, app, service or AI agent gets only the access it needs to do its job, for only as long as it needs it. For APIs, that means each consumer can call only the APIs and operations it uses, see only its own data, and hold short-lived credentials.

Anything else is denied by default.

In January 2024, Microsoft disclosed that a Russian state actor, Midnight Blizzard, had read email from its senior leadership team. The way in wasn't exotic. According to Microsoft's own analysis, the attackers took over a forgotten test account, found a legacy test OAuth application that "had elevated access" to the corporate environment, and used it to grant themselves access to mailboxes.

A test app didn't need corporate mailbox access. Nobody removed it. That's what the principle of least privilege exists to prevent, and APIs are where it's most often ignored.

This guide explains what least privilege means for APIs, why it matters, and how to apply it, measure it and keep it, with code we ran and tested.

Principle of least privilege for APIs infographic showing the four limits on API access (which APIs, which operations, which data, how long), the grant, use, review and remove lifecycle, and the checks that keep access minimal

What is the principle of least privilege?

The principle of least privilege is a security rule: give each identity the minimum access it needs to do its job, and nothing more. It applies to people, applications, services and AI agents alike. It's often shortened to PoLP or POLP.

Definition

Principle of least privilege

The principle of least privilege is a security principle that each entity, whether a user, process or machine, is granted only the minimum authorizations and resources it needs to perform its function. NIST defines it this way in SP 800-53 Rev. 5. The idea dates back to Saltzer and Schroeder's 1975 paper on protecting information in computer systems.

So what is least privilege in plain terms? A delivery driver gets the key to the loading dock, not the master key to the building. If the key is copied, the thief can reach the loading dock and nothing else.

Three ideas sit inside the least privilege principle:

  1. Minimum scope. Grant only the actions and resources the job needs.
  2. Minimum time. Grant access only for as long as it's needed, then remove it.
  3. Deny by default. Anything not explicitly granted is refused.

What does least privilege mean for APIs?

For APIs, least privilege limits four things: which APIs a consumer can reach, which operations it can call, which data it can touch, and how long its credentials work. Most API programs only limit the first, and only loosely.

Here's a principle of least privilege example. A logistics partner needs to show shipment status to its customers. It calls two endpoints: list orders and get one order. Here's what it often receives, and what least privilege looks like:

Over-privileged vs least privilege API access

DimensionOver-privileged accessLeast privilege access
Which APIsOne API key that works on every APIAccess to the Orders API only
Which operationsRead, write, delete and exportorders:read only
Which dataEvery customer's ordersOrders for that partner's own shipments
How longA key that never expiresAccess tokens that expire in minutes, a client reviewed every quarter
Where fromAny network, any clientIts registered client, bound with mTLS

Swipe sideways to see all columns →

Least privilege access doesn't mean making partners ask for permission every week. It means the access they hold matches what they do, and shrinks when what they do changes.

How is least privilege different from zero trust and need-to-know?

Zero trust decides whether to trust each request; least privilege decides how much access to allow once it's trusted. Need-to-know is least privilege applied to information. They work together, not as alternatives.

Least privilege vs zero trust and related principles

ConceptThe question it answersAPI example
Zero trustShould this request be trusted, right now?Verify the token, client and context on every call, even inside the network
Least privilegeHow much access should this identity have?The partner's token carries orders:read only
Need-to-knowWhich information does this identity need?Responses include only the fields the partner needs
Separation of dutiesShould one identity be able to do this alone?Refunds above a limit need a second approver
Zero standing privilegesShould this access exist when nobody is using it?Admin scopes are issued on request, for 15 minutes

Swipe sideways to see all columns →

Why does the principle of least privilege matter for APIs?

Least privilege matters for APIs because most API attacks use valid credentials, and the damage a stolen credential can do equals the access it was given. Attackers rarely need to break authentication. They need one key or token that can reach too much.

The numbers back this up:

Why are APIs harder than user access?

API credentials belong to machines, so nobody notices when they're unused, shared or older than the project they were made for. A person who leaves the company gets offboarded. A partner integration that stops being used often keeps its key for years.

APIs also concentrate access. One API key can read millions of records in minutes, with no human pause. In August 2025, attackers used OAuth tokens stolen from the Salesloft Drift integration to export data from hundreds of companies' Salesforce instances, according to Google's Threat Intelligence Group. Each token could do exactly what it had been allowed to do. The problem was how much that was.

Which standards require least privilege?

Most security and privacy frameworks require least privilege, so it's an audit item as well as good practice. Common ones include:

  • NIST SP 800-53 Rev. 5, control AC-6 (Least Privilege), used by US federal systems and many enterprises.
  • PCI DSS v4.0, Requirement 7, which restricts access to cardholder data by business need to know.
  • HIPAA, whose minimum necessary standard limits use and disclosure of health data.
  • ISO/IEC 27001:2022, Annex A controls on access control and privileged access rights.
  • SOC 2, whose logical access criteria expect access to be authorized and limited to job need.

How do you apply the principle of least privilege to API access?

Apply least privilege to APIs in five layers: derive the minimum access from the API spec, scope each consumer, limit data at the object and field level, limit time with short-lived and just-in-time credentials, and limit where credentials can be used. Each layer shrinks what a stolen credential can do.

How do you design least privilege into API access?

Start from what the consumer needs to call, then derive the scopes from your OpenAPI spec, instead of picking scopes by hand. Hand-picked access drifts toward "give them everything so it works". Derived access starts minimal.

Your OpenAPI file already says which scope each operation needs. This function turns "the operations this client needs" into the smallest scope set, flags high-risk scopes for approval, and refuses operations that don't exist:

Node.js · minimal-scopes.mjs
// minimal-scopes.mjs: derive the smallest scope set from the OpenAPI spec
// Grant only what the operations a client needs require, and flag risky ones
export function minimalScopes(openapi, operationIds, highRisk = []) {
  const byId = {};
  for (const [path, item] of Object.entries(openapi.paths))
    for (const [method, op] of Object.entries(item))
      byId[op.operationId] = { route: `${method.toUpperCase()} ${path}`, security: op.security ?? openapi.security ?? [] };

  const scopes = new Set(), unknown = [];
  for (const id of operationIds) {
    const op = byId[id];
    if (!op) { unknown.push(id); continue; }          // never grant for operations that don't exist
    for (const req of op.security) for (const s of Object.values(req).flat()) scopes.add(s);
  }
  const sorted = [...scopes].sort();
  return { scopes: sorted, needsApproval: sorted.filter((s) => highRisk.includes(s)), unknown };
}

For the logistics partner that needs listOrders and getOrder, it returned one scope, orders:read. For a support tool that needs getOrder and refund, it returned orders:read and payments:refund, with payments:refund flagged for approval.

How do you scope each API consumer?

Give every consumer its own client identity, its own credentials and its own narrow scopes, and decide them per API product, not per platform. Shared keys make least privilege impossible, because you can't remove access from one consumer without breaking the others.

  • Use OAuth scopes to limit operations. Name them resource:action, split read from write, and give export, refund and delete their own scopes. See OAuth scopes explained for scope design.
  • Use roles for groups, attributes for conditions. Roles decide which API products a consumer can subscribe to. Attributes, such as plan, region or tenant, narrow what each call can do. See RBAC vs ABAC for how to combine them.
  • Give API keys a scope too. If you still use API keys, link each key to one client, one plan and a list of APIs, not to "all APIs".

How do you limit which data an API consumer sees?

Least privilege doesn't stop at the endpoint: limit each consumer to its own records and to the fields it needs. A partner with orders:read should still only read its own orders.

That takes object-level and field-level checks inside the service, such as "the order's tenant must match the caller's tenant" and "only finance clients receive the iban field". Missing object checks cause broken object level authorization, the top risk in the OWASP API Security Top 10 (2023). We walk through tested object-level checks in our guide to API authorization.

How do you limit how long access lasts?

Make everyday access short-lived and make high-risk access temporary, issued only on request. Time is the dimension most API programs forget: a key with perfect scopes that never expires is still a standing risk.

  • Short-lived access tokens. Minutes to an hour, so a leaked bearer token stops working quickly.
  • Rotated secrets. Client secrets and API keys rotate on a schedule. See how to rotate API keys automatically.
  • Just in time access for risky scopes. Nobody holds payments:refund all the time. A client requests it, someone approves, and it gets a token that works for 15 minutes.

This is the goal called zero standing privileges: high-risk access doesn't exist until someone needs it. Here's a tested just-in-time elevation:

Node.js · jit.mjs
// jit.mjs: just-in-time elevation. High-risk scopes only with an approval, for 15 minutes
import { SignJWT, jwtVerify } from 'jose';

const ISSUER = 'https://auth.example.com', AUDIENCE = 'https://api.example.com/payments';

export async function issueElevated(key, { client, scope, approval }) {
  if (!approval?.approvedBy || approval.scope !== scope || approval.client !== client)
    throw new Error('approval_required');                       // no standing access to risky scopes
  return new SignJWT({ scope, client_id: client, approval_id: approval.id })  // approval id lands in audit logs
    .setProtectedHeader({ alg: 'ES256' }).setIssuer(ISSUER).setAudience(AUDIENCE)
    .setSubject(client).setIssuedAt().setExpirationTime('15m').sign(key);
}

export async function check(publicKey, token, needed, currentDate = new Date()) {
  const { payload } = await jwtVerify(token, publicKey, { issuer: ISSUER, audience: AUDIENCE, currentDate });
  return payload.scope.split(' ').includes(needed);
}

Without an approval, the request failed with approval_required. With one, the token allowed payments:refund. Sixteen minutes later, the same token failed with ERR_JWT_EXPIRED, and no one had to remember to revoke it.

How do you limit where API credentials work?

Bind each credential to the API it's for and, for high-value APIs, to the client that holds it. Check the token's audience, so a token for the orders API fails on the payments API. Bind tokens to a client certificate (mTLS) or a DPoP key, so a copied token is useless on its own. Restrict partner clients to known networks where that's practical.

How do you enforce least privilege across many API gateways?

Define each consumer's access once and apply it on every gateway, or least privilege breaks at the gateway you forgot. Large organisations run several gateways, each with its own way of granting keys and scopes. A partner removed from one can still call the same API through another.

Teams using the DigitalAPI API Developer Portal let consumers request only the API products and scopes their plan allows, with approval for high-risk ones, so access starts minimal on the first key. The DigitalAPI API Gateway then enforces the same scopes and deny-by-default rules across the gateways you already run, and its usage analytics show which granted scopes each consumer uses.

See how DigitalAPI keeps every API consumer at least privilege across all your gateways → Book a Demo

How do you measure least privilege for APIs?

Measure least privilege by comparing what each consumer is granted with what it uses, then remove the difference. If a scope hasn't been used in 90 days, it probably isn't needed. If a client hasn't called anything in 90 days, it probably isn't needed either.

This gap grows on its own, a problem called privilege creep: projects end, integrations change, people move teams, and access is added but never removed. Access reviews catch some of it. Usage data catches more, because it doesn't depend on someone remembering why a scope was granted.

Here's an audit that reads grants and gateway access logs and reports what to remove:

Node.js · unused-scopes.mjs
// unused-scopes.mjs: find granted scopes a client hasn't used in N days
// grants: { clientId: [scopes] }, log: [{ client, scope, at: ISO date }] from gateway access logs
export function auditGrants(grants, log, { days = 90, now = new Date() } = {}) {
  const since = new Date(now - days * 864e5);
  const used = {};
  for (const e of log) if (new Date(e.at) >= since) (used[e.client] ??= new Set()).add(e.scope);

  return Object.entries(grants).map(([client, scopes]) => {
    const u = used[client] ?? new Set();
    const unused = scopes.filter((s) => !u.has(s));
    return { client, granted: scopes.length, unused,
             action: u.size === 0 ? 'revoke client' : unused.length ? 'remove unused scopes' : 'ok' };
  });
}

We ran all three samples, the scope calculator, the just-in-time elevation and the usage audit, with Node.js 18+ and jose 5.9.6. Every result matched what least privilege should do:

Least privilege test results

TestResult
Scopes for a partner that needs listOrders and getOrderorders:read only
Scopes for a support tool that needs getOrder and refundorders:read, payments:refund, with payments:refund flagged for approval
Scopes for a request that includes a non-existent deleteOrderorders:read; deleteOrder reported as unknown, nothing granted for it
Audit: partner holding orders:export, last used 8 months agoRemove orders:export
Audit: billing service using both of its scopesOK
Audit: pilot client with no calls in 90 daysRevoke the client
Just-in-time request for payments:refund without approvalRefused: approval_required
Approved just-in-time token, used right awayAllowed
Same token, 16 minutes laterRejected: ERR_JWT_EXPIRED

Swipe sideways to see all columns →

Least privilege test results showing the minimal scopes derived from an OpenAPI spec, unused scopes and inactive clients found in a 90-day usage audit, and a just-in-time token refused without approval and expired after 15 minutes

Track three numbers over time: the share of granted scopes used in the last 90 days, the number of clients with no calls in 90 days, and the number of standing high-risk grants. Least privilege is improving when the first rises and the other two fall.

Least privilege lifecycle for API access showing four stages, grant minimal access from the spec, use short-lived tokens, review usage every 90 days, and remove unused scopes and clients, with just-in-time elevation for high-risk scopes

How does least privilege apply to AI agents and MCP?

Give each AI agent its own identity, only the tools it needs, short-lived tokens, and human approval for anything destructive. Agents act quickly, without supervision, and can be steered by the content they read, so their access should be narrower than a person's, not wider.

  • One identity per agent. Don't let agents reuse a person's session or a shared service account. You need to know which agent did what, and to revoke one without affecting the rest.
  • Scope tools, not only APIs. Expose only the tools an agent needs, with read and write tools behind separate scopes.
  • Act for the user, not as a super user. When an agent works for a person, its token should carry that person's limits plus the agent's own, never more than either.
  • Use just-in-time for writes. Refunds, deletes, bulk exports and sending messages should need a fresh approval.
  • Log every tool call with the agent, the user it acted for, and the decision.

The MCP authorization specification builds on OAuth, so the same scope and audience rules apply to MCP servers. For the setup, see how to manage AI agent permissions with MCP authorization.

What are the most common least privilege mistakes for APIs?

The most common least privilege mistakes are shared credentials, broad default access, access that never expires, and access nobody reviews. Each one looks harmless until a credential leaks.

Common least privilege mistakes for APIs and fixes

MistakeWhat happensFix
One API key for all APIsA leaked key reaches everythingOne client per consumer, scoped per API product
"Full access" as the default planEvery new consumer starts over-privilegedStart from zero; derive scopes from the operations requested
Shared credentials across teams or agentsCan't revoke one user without breaking othersOne identity per app, service and agent
Keys and secrets that never expireOld integrations keep live access for yearsExpiry dates, rotation and short-lived tokens
Standing admin or export scopesThe most dangerous access is always onJust-in-time elevation with approval
Test and pilot apps with production accessA forgotten app becomes the way in, as at Microsoft in 2024Separate environments; remove test grants after the pilot
Checking the endpoint but not the dataAny customer's records are one ID change awayObject- and field-level checks in the service
Reviewing access from spreadsheets onlyReviewers approve whatever they don't recogniseReview against 90-day usage data
No owner for each clientNobody can say whether access is still neededRecord a business owner and review date per client

Swipe sideways to see all columns →

Least privilege implementation checklist for APIs

Use this checklist to apply the principle of least privilege to an API program. Work through it per API product, starting with the APIs that hold the most sensitive data.

Your APIs follow least privilege if

  • Every consumer has its own client and credentials.
  • Scopes are derived from the operations each consumer uses.
  • High-risk scopes are issued just in time, with approval.
  • You can show which granted scopes were used in the last 90 days.

You have a least privilege gap if

  • A key or token works on APIs its owner doesn't use.
  • Credentials have no expiry date or owner.
  • Test, pilot or former partner apps still have production access.
  • Nobody has removed a scope in the last quarter.
  1. Inventory every API consumer: partners, internal apps, services, scripts and AI agents, each with a named owner.
  2. Give each one its own client identity and retire shared keys.
  3. Classify your scopes into everyday and high-risk, such as export, refund, delete and admin.
  4. Derive each consumer's scopes from the operations it needs, using your OpenAPI spec.
  5. Deny by default at the gateway: unmapped routes and missing scopes are refused.
  6. Enforce object- and field-level checks in each service, so consumers see only their own data.
  7. Set token lifetimes to minutes or an hour, and rotate secrets and keys on a schedule.
  8. Move high-risk scopes to just-in-time access with approval and a short expiry.
  9. Check audience and bind tokens to the client for high-value APIs.
  10. Separate environments, so test and sandbox clients can't reach production.
  11. Audit usage every 90 days and remove unused scopes and inactive clients.
  12. Offboard immediately when a partner contract, project or agent ends.
  13. Log every access decision with client, scope, object and outcome.

Key takeaways

  • The principle of least privilege gives each identity only the access it needs, only for as long as it needs it.
  • For APIs, limit four things: which APIs, which operations, which data and how long.
  • Most API attacks use valid credentials, so the access each credential holds decides the damage.
  • Derive scopes from the spec, issue risky scopes just in time, and expire everything.
  • Measure least privilege with usage data: remove scopes and clients unused for 90 days.

Frequently asked questions

1. What is the principle of least privilege?

The principle of least privilege is a security rule that every user, application, service or AI agent gets only the minimum access it needs to do its job, and nothing more. NIST SP 800-53 defines it as granting each entity only the authorizations and resources it needs to perform its function. Access that isn't needed is denied by default.

2. What is an example of the principle of least privilege?

A logistics partner that only shows shipment status should get a token with orders:read for the Orders API, limited to its own shipments, expiring in minutes. Least privilege is violated if the same partner holds a permanent key that can write, delete and export every customer's orders across all APIs.

3. Why is least privilege important for API security?

Least privilege is important because most API attacks use valid credentials. Salt Security's 2025 report found 95% of API attacks came from authenticated sources. When a key or token leaks, attackers can do exactly what it allows, so narrow, short-lived access limits the damage of every breach.

4. What is the difference between least privilege and zero trust?

Zero trust is a security model that verifies every request and never trusts a network location by default. Least privilege is a principle that limits how much access each identity has. Zero trust decides whether to trust a request; least privilege decides what the trusted identity may do. Zero trust architectures depend on least privilege.

5. What is privilege creep?

Privilege creep is the gradual build-up of access an identity no longer needs. It happens when people change roles, projects end or integrations change, and new access is added but old access isn't removed. For APIs, it shows up as old partner keys, unused scopes and test apps that keep production access.

6. What is just-in-time access?

Just-in-time access grants elevated permissions only when they're requested and approved, for a short time, after which they expire automatically. For APIs, a client might request a payments:refund scope, receive approval, and get a token that works for 15 minutes. It removes standing access to the most dangerous operations.

7. What are zero standing privileges?

Zero standing privileges is a goal where no identity holds high-risk access permanently. Admin, export, delete and payment permissions are issued just in time, for a single task, and expire on their own. It reduces what an attacker can do with any credential stolen while no task is in progress.

8. How do you measure least privilege?

Measure least privilege by comparing granted access with used access. Track the share of granted scopes used in the last 90 days, the number of clients with no recent calls, and the number of standing high-risk grants. Remove unused scopes and inactive clients, and review the numbers every quarter.

9. How does least privilege apply to API keys?

Each API key should belong to one consumer, be limited to the APIs and operations that consumer needs, have an owner and an expiry date, and be rotated on a schedule. Never issue a key that works across all APIs. For sensitive APIs, replace long-lived keys with short-lived OAuth access tokens.

10. How do you apply least privilege to AI agents?

Give each AI agent its own identity, only the tools and scopes its task needs, short-lived tokens, and human approval for destructive or high-value actions. When an agent acts for a person, its access should never exceed that person's own. Log every tool call with the agent and the user it acted for.

Conclusion

The principle of least privilege is more than 50 years old, and still the control that most decides how bad an API breach gets. Attackers increasingly don't break in. They log in with a key or token someone forgot, and take whatever it was allowed to reach.

For APIs, least privilege comes down to four limits: which APIs, which operations, which data and how long. Derive access from the spec, give every consumer its own identity, issue risky scopes just in time, expire everything, and let usage data tell you what to remove. For the wider picture of keys, tokens and roles, read the ultimate guide to API access control.


How safely do you grant API access to partners and AI agents? Get your free readiness score: Check Your API Access Readiness

Prefer a walkthrough?
Book a Demo
About the author
Dhayalan Subramanian

Dhayalan Subramanian is Associate Director, Product Growth at DigitalAPI, where he leads go-to-market and product growth for the company’s multi-gateway API management platform. His work focuses on helping large enterprises and mid-market cloud companies consolidate APIs across AWS, Azure, Apigee, Kong, MuleSoft, and other gateways into a single control plane for governance, discovery, monetization, and agent consumption.

‍

Dhayalan brings 14+ years of experience across product strategy, enterprise architecture, and engineering leadership. Earlier in his career, he held senior roles at Encora (as Associate Architect and Technical Manager), Mindtree (Technology Lead), Tech Mahindra (Technical Lead), and Primus Analytics, where he designed integration frameworks and delivered enterprise-grade digital platforms for global customers.

‍

At DigitalAPI, he works directly with platform, integration, and developer experience leaders at Fortune 500 organizations to operationalize unified API catalogs, developer portals, and MCP-ready APIs. He writes regularly on API developer experience, API governance, and AI agent architectures.

Become AI-ready
Make every API agent-callable.
An 8-week pilot. We connect to your gateways, ship MCP-callable APIs, and onboard your first agent.
0 rip-and-replace
Same auth, same audit
Live in production in 8 weeks
Get started

One email a fortnight. Worth opening.

A short digest of what we're writing, what we're learning from customers, and the handful of links you'd actually want from us. No tracking pixels.

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.