How to distinguish identity proof, access decisions, delegation, context, and enforcement in enterprise APIs
In-depth edition - study material and professional reference
By João Ricardo Dutra••Complete material
From identity to access decision in a corporate API
Opening figure - Access security is a chain of contextualized proofs, assertions and decisions.
Central principle
Authenticate proves who or what is calling; authorize decides what this identity can do now.
In-depth edition - study material and professional reference
Chapter presentation
The previous chapter expanded the communication repertoire by introducing GraphQL, gRPC and WebSocket. Regardless of the protocol or style adopted, any corporate interface needs to answer two fundamental questions: who or what is making the call and what that identity can do in that context. An API should not accept an operation just because the message arrived via HTTPS or contains a header called . It is necessary to identify the caller, validate the evidence presented, understand in whose name the operation is performed and apply a coherent policy to the requested resource.
Identity in APIs involves people, applications, devices and workloads. These subjects have different life cycles, registration forms and credentials. A user can authenticate with multiple factors; an application can use certificate, asymmetric key or ; a pod can be assigned a short identity by attestation from the environment. Treating everyone as username and password produces static secrets, low traceability and excessive authorizations.
and are separate responsibilities. establishes that a matches an identity under a certain level of trust. evaluates whether this identity can perform a specific action on a resource, considering , tenant, attributes, relationship, risk and domain state. Strong cannot compensate for a broad or non-existent policy.
This chapter builds the conceptual foundation for later chapters on credentials, OAuth 2.0, OpenID Connect, and tokens. The limits between and , identity elements, sessions, claims, / / /PBAC models, , , / architecture, 401/403 responses, observability and application in API Gateways will be studied. Basic Auth, Digest, API Keys and OAuth appear only at the level necessary to establish conceptual differences; its details will be deepened in the following chapters.
How to study this chapter
In each example, identify subject, principal, , authenticator, , , resource, policy and enforcement point. This decomposition avoids the generic conclusion that “the token is valid” when the access decision is still incorrect.
Learning Objectives
Differentiate identity, subject, principal, , authenticator, session, token and .
Separate , , , and auditing.
Distinguish human identities, applications, devices and workloads.
Evaluate API keys, Basic, cookies, secrets, certificates, tokens and proof-of-possession mechanisms.
Validate JWTs considering algorithm, key, , , time, type and policy.
Understand the role of OAuth 2.0 and OpenID Connect without confusing with proof of login.
Compare , , , and attribute-and context-oriented policies.
Design , , PIP and PAP in architectures with gateway and services.
Apply , managed identity, and SPIFFE in machine-to-machine integrations.
Diagnose 401, 403 errors, rejected tokens, missing claims and divergent decisions between gateway and backend.
Chapter structure
14.1 Identity as the foundation of access control
14.2 Vocabulary: subject, principal, and session
14.3 , , and audit
14.4 Human identities, applications, devices and workloads
14.5 Registration, link and identity life cycle
14.6 User Factors and Authenticators
14.7 Application credentials and proof-of-possession
14.8 API keys: usefulness and limitations
14.9 HTTP Basic and static credentials
14.10 Sessions, cookies, CORS and CSRF
14.11 Opaque, structured, bearer and sender-constrained tokens
14.12 Claims, , subject, , scopes and roles
14.13 : structure and secure validation
14.14 OAuth 2.0 and OpenID Connect: conceptual limits
14.15 , , and PBAC models
14.16 , , PIP and PAP
14.17 , impersonation and on-behalf-of
14.18 and zero trust
14.19 Identity in API Gateways, Axway and Azure
14.20 Responses 401, 403 and insufficient_scope
14.21 Logs, auditing, privacy and correlation
14.22 Threats and hardening
14.23 Evidence-driven troubleshooting
14.24 Case studies and labs
Summary, checklist, exercises, glossary and references
14.1 Identity as the foundation of access control
An API exposes business capabilities, data, and transitions. To protect them, the system needs to associate each request with a trusted principal. The principal is the operational identity used in the decision: a person, an application, a device, a workload or a combination, such as “application X acting on behalf of user Y”. Without this association, rate limits, audit trails, and authorizations become approximations based on IP or shared secrets.
Identity is not synonymous with textual name. An email, client_id or SPIFFE ID is an identifier; trust arises from the process that links this identifier to a and the validation performed on each use. Two systems can use the same text and have different trust domains. Therefore, the identifier needs to be interpreted according to the , tenant, type of subject and registration policy.
In intermediary architectures, each hop can authenticate different identities. The balancer can authenticate the gateway certificate; the gateway can validate the consumer's ; the backend can receive propagated claims or a new token issued to the internal segment. The design must state where identity is established, transformed, reduced or replaced.
Architecture rule
Never use just a value provided by the client itself, such as X-User-Id or X-Role, as proof of identity. The data must come from a validated or be inserted by a trusted intermediary that removes any external values.
14.2 Subject, principal, , authenticator and session
The subject is the entity about which a statement is made. In human , it can be a registered person. In an integration, it could be a service. The principal is the representation of this entity within the security system. The same person can have different principals in different tenants; An application can operate as its own principal or act on behalf of a user.
is the material used to demonstrate control or link: password, private key, certificate, client secret, physical authenticator, session cookie or token. The authenticator is the mechanism that contains or produces the proof. In digital identity terminology, the process verifies that the claimant controls one or more authenticators linked to the subscriber.
Session is state created after to avoid repeating the complete process in each interaction. Tokens can represent session, or , but they are not automatically the same thing. A browser session can exist at the identity provider while the API receives independent, short-lived access tokens.
Table 1 - Close terms have different responsibilities.
Term
Question answered
Example
Identifier
How is the entity named?
sub, client id, SPIFFE ID. _
Credential
What material is presented?
password, key, certificate, token.
Authentication
Is the proof valid for this identity?
MFA, subscription, mTLS.
Session
What temporary state was created?
secure cookie or session on the IdP.
Authorization
Is the action permitted in this context?
scope, role, attribute and domain rule.
Figure 1 - An authenticated identity still needs to undergo a contextual decision.
14.3 , , and audit
validates a proof. decides access. allows a client to obtain limited authority to act on behalf of another subject. allows a domain to accept assertions produced by another trusted domain. Audit records enough facts to reconstruct who did what, on which resource, with what decision and what result.
These functions can occur in different components. An identity provider authenticates the user; an server issues an ; API Gateway validates the token and applies cross-cutting policies; the backend checks fine related to the resource state. Focusing every decision on the gateway may require domain data that it does not have; concentrating everything on the backend doubles controls and reduces governance.
The design must separate decision and enforcement. A policy can be evaluated locally by the gateway, by a central service, or in conjunction with the backend. Regardless of the model, the request must carry verifiable context and the decision must be recordable. Invisible identity transformations create confusion in incidents and audits.
Table 2 - The functions are linked, but should not be confused.
Function
Primary input
Exit
Authentication
credential, proof and context
authenticated principal and trust level.
Authorization
principal, action, resource and attributes
allow, deny or require additional condition.
Delegation
consent or authority granted
limited token to act on behalf of another.
Federation
assertion of another domain
identity accepted according to trust policy.
Audit
events and decisions
correlated and investigateable trail.
14.4 Human identities, applications, devices and workloads
Human identities have characteristics such as employment, personal account, consent, recovery and multi-factor . The risk includes phishing, session hijacking, account sharing, and use after shutdown. usually considers function, unit, relationship with the resource and actions carried out in one's own name.
Applications and workloads are non-human identities. They do not enter a password or respond to a second factor. They require provisioned credentials, environment attestation, or . The life cycle must follow deployment, rotation, change of owner and deactivation. A secret without an owner and without expiration is an operational and security debt.
Devices can provide posture, registration, or hardware-protected key signals. Device identity does not replace user or application identity; it adds context. A request can simultaneously involve the user, OAuth client, device and workload that runs the backend. Claims and logs need to preserve these layers without collapsing them into a single field.
Table 3 - Each identity class requires its own controls.
Type
Typical identifier
Preferred credential
Lifecycle risk
Human
subject by tenant
phishing-resistant MFA when applicable
shutdown, recovery and session.
Application
client id / service principal _
asymmetric key or federation
orphan secret and broad permissions.
Workload
service account / SPIFFE ID
short credential issued by attestation
ephemeral replica and shared identity.
Device
device ID and key
protected key and registry
loss, cloning or outdated posture.
14.5 Registration, link and identity life cycle
Secure starts before login. The registry needs to establish who can create the identity, which attributes are trusted, who is the owner and how the link will be revoked. In human identities, this may involve identity proofing and HR processes. In applications, it involves registration, technical owner, environment, purpose, repository and approval of permissions.
The lifecycle includes creation, activation, change, suspension, recovery, rotation, and termination. Control should not depend solely on removing a : roles, grants, sessions, refresh tokens, certificates and associations in catalogs also need to be invalidated. Deactivating the account without closing sessions can maintain access for hours or days.
Shared identities eliminate accountability. When multiple systems use the same client_id and secret, it is impossible to accurately assign traffic, enforce least privilege, or remove just one consumer. Identity individualization enables per-application quotas, policies, telemetry, and incident response.
Minimum registration control
Every application identity must have owner, purpose, environment, review date, mechanism, approved permissions and deactivation procedure. The absence of any item shall prevent promotion to production.
14.6 User Factors and Authenticators
factors are often grouped into something the user knows, has, or is. The number of factors is not enough to determine resistance: two memorized secrets are not equivalent to two independent factors. It is also necessary to evaluate resistance to phishing, replay, authenticator theft, recovery and binding between session and context.
In APIs accessed by interactive applications, user typically occurs at the identity provider, not directly at the business endpoint. The API receives a resulting assertion or . This allows you to centralize MFA, risk, and session policies, while the API focuses on validating the token and authorizing the resource.
The level may vary per action. Querying low-risk data can use existing session; Changing the limit or registering a beneficiary may require a step-up. Claims such as acr and amr can carry information about the method, but the consumer must only interpret values documented by the and appropriate to the policy.
Table 4 - Factors and signs must be evaluated according to the risk of the journey.
Category
Example
Note
Knowledge
password or PIN
vulnerable to phishing, reuse and leakage.
Possession
security key or authenticator app
Security depends on protection and binding.
Inherence
biometrics
typically unlocks an authenticator; requires care with privacy.
Context
device, network, risk
it is an additional sign, not a universal isolated factor.
14.7 Application credentials and proof-of-possession
Applications can use shared secret, certificate, private key, message signature, mTLS, or identity . Secrets are simple, but any copy allows impersonation. Asymmetric keys reduce secret distribution: the private key remains on the client and the verifier uses the public key or certificate.
Proof-of-possession means that the client demonstrates control of the key, not just presenting a copiable value. mTLS ties to the certificate used in the channel. DPoP adds signed proof at the HTTP level and can bind tokens to a key. These mechanisms reduce replay of stolen tokens, but require validation of nonce, method, URI, thumbprint and time window according to the protocol.
Workload avoids storing long-lived secrets. An external environment presents a short assertion from its provider; The target domain validates , subject and conditions and issues a local token. The trust must be restricted to specific subjects and audiences, never to any token issued by the provider.
Table 5 - Application credentials must prioritize proof-of-possession and automation.
Mechanism
Material at the customer
Advantage
Caution
Client secret
copiable secret
broad support
rotation, pouring and distribution.
Certificate / private key
asymmetric key
cryptographic proof and public key separation
key protection and certificate cycle.
mTLS
certificate in handshake
channel authentication and token binding possible
TLS termination and proxies.
Federation
short environmental assertion
no local static secret
trust policy needs to be specific.
14.8 API keys: usefulness and limitations
An is a secret or semi-secret identifier associated with a consumer, product or plan. It is useful for metering, quotas, abuse discovery, and traffic separation. However, it does not automatically represent a strong identity. If copied, it can be reused by any party, and many implementations have no , short expiration, or proof of ownership.
API keys should not be sent in a query string, because URLs appear in logs, history, analytics and refereers. Prefer dedicated header or as per contract. The value must be treated as a secret: stored securely, displayed only once, rotatable and never fully recorded.
In low-risk public APIs, a key can complement controls. In sensitive operations, it must be combined with appropriate and . The gateway can validate the key and apply plan, but the backend still needs to authorize the resource when identity or business context matters.
Header transport example
GET /catalog/products HTTP/1.1
Host: api.company.example
X-API-Key: <secret-value>
Antipattern
Do not use GET /recurso?api_key=secret. The URL can be registered by proxies, servers, APM tools and browsers, expanding the exposure surface.
14.9 HTTP Basic and static credentials
HTTP Basic transports a Base64 encoded identifier and password. Base64 is not encryption; the mechanism relies on TLS for confidentiality. The header can be resent on each request and, when a is shared, any leakage allows use until rotation.
Basic still appears in legacy integrations and administrative endpoints. Use should be limited to protected channels, individual credentials, minimum , rate limiting and rotation. Never reuse a human directory password as an integration password. A service must have its own lifecycle and owner.
The migration can accept Basic and token during controlled window, register remaining consumers and retire the old mechanism. Just converting username/password into a token at the gateway without improving registration, rotation and preserves the original fragility.
Conceptual framework
Authorization: Basic base64(client-id:secret)
# The decoded content remains a reusable secret.
14.10 Sessions, cookies, CORS and CSRF
Browser applications often use session cookies. The browser automatically sends them to the corresponding domain, which creates the risk of cross-site request forgery when a malicious origin induces an authenticated request. SameSite, anti-CSRF tokens, Origin validation and appropriate methods reduce risk; CORS is not a complete protection mechanism against CSRF.
Session cookies must use Secure, HttpOnly when they do not need to be read by JavaScript, minimum Domain/Path , and architecturally compatible SameSite policy. The session identifier must be unpredictable and rotated upon or elevation of privilege. Logout needs to terminate state on the server when the session is stateful.
In SPAs, storing bearer tokens in localStorage increases the impact of XSS. A backend-for-frontend architecture can maintain tokens on the server and expose only protected session cookies to the browser. The choice depends on the threat model, but the design needs to consider XSS, CSRF, exfiltration, refresh and multiple tabs.
does not protect against compromised script or server.
HttpOnly
reading by JavaScript
reduces direct exfiltration by XSS.
SameSite
cross-site shipping
needs to support federated login and legitimate flows.
Origin/CSRF token
induced request
the server must validate on effective operations.
14.11 Opaque, structured, bearer and sender-constrained tokens
An opaque token does not reveal meaning to the client. The resource server queries introspection or local state to discover activity, subject, and expiration. This facilitates revocation and reduces exposure of claims, but introduces dependence on network, cache and availability of the server.
A structured token, such as , carries locally verifiable claims. This reduces calls per request, but immediate revocation is more difficult and the content can be copied during its validity. Signature guarantees integrity and origin, not confidentiality. The payload of a JWS is normally just encoded and can be read.
grants access to whoever holds it. requires additional proof of legitimate client, such as mTLS or DPoP. Binding reduces replay, but does not eliminate the need for short expiration, correct , minimum and protection of the issuing endpoint.
Table 7 - Possession format and model are different decisions.
Type
Validation
Advantage
Limitation
Opaque
introspection or local storage
revocation and little exposure
latency and core dependency.
JWT signed
public key and claims
local validation and interoperability
replay and revocation until expired.
Bearer
possession of value
simplicity
theft allows reuse.
Sender-constrained
token plus proof of key
reduces replay by third parties
greater operational complexity.
14.12 Claims, , subject, , scopes and roles
Claims are statements about the token, subject, client or context. iss identifies the ; sub identifies the subject in the 's domain; aud indicates the intended recipient; exp, nbf and iat establish time; jti can identify the token. The iss + sub combination is safer than interpreting sub alone.
represents delegated authority in terms understandable by the resource server. Role usually represents a role assigned to a user or application. Permission or entitlement can express more specific capabilities. Mixing everyone into the same camp makes politics ambiguous. The organization needs to define vocabulary, namespace and semantics.
Claims must not carry unnecessary or sensitive data. Tokens pass through clients, gateways, logs and tools. When the backend needs dynamic information, it can search data by identifier or use an attribute service. Very large claims increase headers, latency and exposure risk.
Table 8 - Claims need explicit semantics and validation.
claim
Meaning
Validation
iss
who issued
exact comparison with trusted issuer.
sub
subject at the issuer
interpret along with iss and type of identity.
aud
recipient resource
must include the expected API.
exp/nbf
time window
use reliable clock and limited skew.
scope
delegated authority
require only the scopes necessary for the operation.
azp/clientid_
authorized customer
distinguish user application.
Figure 2 - Signing is just one step in validating a token.
14.13 : structure, signature, encryption and secure validation
is a claims format that can be protected by JWS or JWE. In a signed , header, payload and signature are encoded in separate segments. The header indicates cryptographic parameters; the payload contains claims; the signature protects integrity. JWE adds encryption, but it should not be introduced just to hide excessive data design.
Validation needs to fix accepted algorithms and reject unexpected combinations. The verifier should not blindly trust alg or key URLs provided by the token. Keys must come from trusted configuration or metadata, with caching, rotation, and protection against confusion between symmetric and asymmetric keys.
In addition to the signature, validate , , exp, nbf, token type and mandatory claims. A valid for an OpenID Connect client must not be accepted as an by an API. Explicit typing, distinct rules, and separate audiences reduce substitution between contexts.
Accepting only a valid signature without checking iss, aud, time and type is equivalent to accepting credentials issued to other systems. Each API needs to declare exactly which issuers, audiences, algorithms and claims are allowed.
14.14 OAuth 2.0 and OpenID Connect: conceptual limits
OAuth 2.0 is a delegated framework. It defines roles and mechanisms for a client to obtain an and access a resource server with limited authority. OAuth does not alone define how the user was authenticated nor does it guarantee that an contains human identity. Client Credentials, for example, represent application access on its own behalf.
OpenID Connect adds an layer on top of OAuth 2.0. The communicates claims about user to the client, and the UserInfo Endpoint can provide additional data. The is intended for the client and should not be sent as a generic for APIs, unless there is an explicit contract and an appropriate profile.
The API must validate intended for it. The client validates intended for it. Confusing the two can allow token substitution. The next chapters will delve deeper into code, PKCE, client credentials, refresh, consent, metadata, introspection and modern security according to OAuth Security BCP.
Table 9 - Identity artifacts have different audiences and uses.
Artifact
Recipient
Purpose
Access token
resource server/API
authorize access to resources.
ID token
OpenID Connect client
inform user authentication result.
Refresh token
authorization server
obtain new access tokens as per policy.
Authorization code
endpoint token by client
short-term intermediate exchange.
14.15 models: , , and PBAC
assigns roles to principals and permissions to roles. It's simple for stable organizational roles, but overly granular roles produce explosion and broad roles violate least privilege. The “analyst” role does not answer on its own whether the user can consult any account or just those in their portfolio.
evaluates attributes of the subject, resource, action and environment. Can combine unit, classification, tenant, time, device and risk. Flexibility increases the need for reliable data, clear semantics, and testing. Outdated or manipulable attributes make the policy insecure.
uses relationships, such as owner, member, responsible or manager. It is useful when access depends on the subject's position in a graph. PBAC is a broad term for policy-based decisions, often combining roles, attributes, and relationships. In real systems, hybrid models are common.
Table 10 - Models can be combined by layer and risk.
Model
Basis of the decision
Proper use
Risk
RBAC
function or role
stable organizational permissions
role explosion and excess privilege.
ABAC
attributes and context
contextual and multitenant rules
incorrect attributes and complex policy.
ReBAC
relationships between entities
owner, team, portfolio and share
outdated graph or expensive query.
PBAC
declarative policy
centralized combination of signals
dependence on PDP and governance.
Figure 3 - Enforcement can remain at the gateway or service while the decision uses external policy and attributes.
14.16 , , PIP and PAP
The Policy Enforcement Point intercepts the operation and applies the decision. API Gateway is a natural for , , quota and cross-cutting rules. The backend also acts as for domain . Policy Decision Point evaluates policies and returns a decision, possibly with obligations such as masking fields or requiring step-up.
The Policy Information Point provides attributes: user data, tenant, relationship, resource classification, or risk. The Policy Administration Point is where policies are created, reviewed, versioned and published. Separating these roles allows for governance, but adds latency, availability and consistency as architectural requirements.
Centralized decisions need caching and fail behavior strategies. Fail-open can expose data when the fails; fail-closed may cause unavailability. The choice depends on the risk of the operation. Critical policies must have testing, versioning, rollback and observability equivalent to production code.
Recommended division
Use the gateway to validate credentials and apply controls independent of domain state. Keep in service decisions that depend on ownership, balance, transaction status, or rules that change with the business.
14.17 , impersonation and on-behalf-of
grants limited authority to a client to act on behalf of a subject. The token needs to distinguish user, client and delegated . Registering only the user hides which application performed the action; registering only the application loses the person who authorized it. Logs must preserve both when the flow involves both.
Impersonation is stronger: one component takes on the identity of another. It must be rare, explicitly authorized and audited, as it eliminates boundaries. In administrative tools, the interface needs to indicate that the operator is acting as another user and record the original actor, reason and duration.
On-behalf-of occurs when one service calls another while maintaining user context. Forwarding the same token to all backends expands and exposure. Token exchange or issuance of a specific token for the next resource reduces privilege and allows representing the chain of actors in a controlled way.
Table 11 - The actor's identity must not disappear during delegation.
Scenario
Identities that must appear
Control
App on behalf of the user
user + client
delegated scopes and consent/policy.
Service on behalf of the user
user + calling service
specific audience and actor chain.
App-only
application/workload
application and owner permissions.
Administrative impersonation
operator + assumed subject
approval, deadline, reason and reinforced audit.
Figure 4 - Attestation and short credentials reduce persistent secrets in workloads.
14.18 and zero trust
represents running software. In the cloud, it can be principal service or managed identity. In Kubernetes, you can use federated service accounts. In SPIFFE, the workload receives a SPIFFE ID and verifiable identity documents through the Workload API. The goal is to link credentials to the actual process environment and lifecycle.
Zero trust does not mean distrusting everything in the abstract; means not granting implicit trust just by network location. Each access must evaluate identity, resource and context. Being inside the VNet or cluster does not replace . Network segmentation remains useful, but it works alongside identity.
Short, automatically rotated credentials narrow the window for abuse. The service should not be able to export a long-lived when the platform can issue tokens on demand. needs to limit and permissions; a managed identity without a secret can still be dangerous if it has an administrator role.
Table 12 - Workload identity must follow the platform and execution cycle.
Technology
Identity
Emission
Usage
Managed identity
managed core service
Azure platform issues tokens
access to resources that trust Microsoft Entra.
Workload federation
mapped external subject
exchange assertion for local token
CI/CD, Kubernetes and multi-cloud without secret.
SPIFFE/SPIRE
SPIFFE ID
Short SVID via attestation
mTLS or JWT across workloads.
Static service account
service account
secret or persistent token
legacy; requires rotation and restraint.
14.19 Identity in API Gateways, Axway and Azure
An API Gateway can extract credentials, validate , certificate or , apply scopes, query external identity and propagate context to the backend. The policy should remove client-supplied identity headers and insert only validation-derived values. The backend should trust these headers only when the connection comes from the authorized gateway.
In Azure API Management, policies such as validate- and validate-azure-ad-token validate tokens and can require , , and claims. The configuration needs to use correct metadata and keys, log failures without exposing token, and separate gateway from domain rules. Managed identity can be used by the gateway or backend to obtain tokens without static secrets in supported scenarios.
In Axway API Gateway, OAuth filters, OpenID Connect, and verification can participate in policies. The design must declare whether the gateway acts as an server, client or resource server. As products and versions vary, the policy needs to be tested with real authorized tokens, key rotation, and error scenarios.
Conceptual example of policy in Azure API Management
validation depends on metadata, key cache and rotation. Test the behavior when the kid changes, the metadata becomes unavailable, the clock diverges, or the token has multiple audiences.
14.20 Responses 401, 403 and insufficient_scope
HTTP 401 indicates that the request does not have valid credentials for the resource. The response must use WWW-Authenticate when applicable, providing the schema and secure parameters. The code does not necessarily mean “non-existent user”; may represent missing, expired token, invalid subscription, or incorrect .
HTTP 403 indicates that the server understands the request and refuses to serve it. It can occur when the identity is valid but does not have permission. On some sensitive resources, the server may prefer 404 to not reveal existence, as long as the behavior is consistent and documented.
When using bearer tokens, errors such as invalid_token and insufficient_scope help the client, but details should not reveal keys, internal rules or existence of data. The gateway and backend need to internally record the exact cause and expose a stable, correlatable, and safe error to the consumer.
Table 13 - External status must preserve semantics; the internal log preserves diagnosis.
Access logs must record principal, identity type, client, , , operation, resource, decision, policy version and correlation ID. Do not register , secret, password, cookie or complete key. When an identifier is sensitive, use pseudonymization or controlled stable hashing as needed for investigation.
The audit needs to distinguish successful , denied , and infrastructure failure. A 401 for expired token is different from an error when fetching metadata. A 403 from the gateway is different from a 403 from the backend. Fields like decision_source and response_origin reduce guesswork-based investigations.
Retention and access to logs must respect privacy and purpose. Profile claims should not be copied in full for all events. Register only attributes necessary for security, support, and compliance. Administrative trails of policy and grant changes are as important as call logs.
Table 14 - Useful audit records identity and decision without leaking credentials.
Field
Example
Caution
principal_id
iss + normalized sub
do not use changeable email as unique key.
clientid_
calling application
preserve in delegated streams.
auth method_
mTLS, JWT, session
do not record credential material.
decision
permit/deny
include policy and point you decided.
correlation id _
end-to-end identifier
validate and normalize external value.
14.22 Threats and hardening
stuffing and password spraying exploit reused passwords. Phishing captures session or factor. Secret leakage exposes application credentials in repositories and pipelines. Token replay reuses bearer tokens. Confusion attacks make a system accept tokens from another context. Broken Object Level allows access to another user's resource even with a valid token.
Hardening starts with least privilege, short credentials, automatic rotation, and separation. JWTs must follow good algorithm, typing and validation practices. Redirect URIs, clients and scopes need to be restricted. Sessions and refresh tokens must have revocation and anomaly detection according to risk.
must occur on every object and function, not just the generic endpoint. Listing /contas with contatos.read does not guarantee that the subject can see all returned accounts. The backend needs to filter by relationship and prevent manipulated IDs from bypassing the rule.
Table 15 - Valid tokens do not eliminate authorization and lifecycle failures.
Threat
Flaw exploited
Primary control
Token replay
copyable bearer
TLS, short expiration and sender constraint when necessary.
Token substitution
audience/type not validated
aud, iss, typ and rules separated by token.
BALL
object without ownership check
authorization per object in the service.
Secret leakage
persistent credential in code
vault, federation and scanning.
Privilege creep
accumulated grants
periodic review and lifecycle.
14.23 Evidence-driven troubleshooting
The investigation begins by identifying who produced the response. Check if the request reached the gateway, if there was a , which policy was executed and if the backend was called. A 401 generated at the edge will not appear in the application log. A 403 from the backend may occur after the gateway accepts the token.
For , extract headers and claims only in a secure environment, without pasting production tokens on external websites. Compare iss, aud, exp, nbf, typ, kid, scopes and client_id with the configuration. Confirm gateway clock, OpenID discovery, JWKS, and key rotation. Valid subscription with wrong should continue to be rejected.
For , reproduce with the same principal and resource. Check attributes, tenant, ownership, policy version and cache. A newly granted permission may not appear due to replication delay or old token. Issuing a new token may be necessary when claims are incorporated at the time of issuance.
Table 16 - Diagnosis needs to correlate credential, decision and response point.
Symptom
Hypotheses
Evidence
401 flashing
expiration, clock skew, key rotation
timestamps, kid, JWKS and gateway node.
403 only on some IDs
ownership or tenant
resource, principal, and domain rule.
Works on portal, script fails
audience, client type or credential
compared tokens and flow used.
Gateway accepts, backend rejects
propagation or divergent policy
reliable headers, internal audience and logs of both hops.
After grant still denies
old token/cache
iat, policy version, and attribute TTL.
14.24 Case studies and labs
Case 1 - accepted as
A SPA uses the returned by the provider to establish the user's local session, reading sub and email without validating or type. A token destined for another API is presented and accepted by the application. The signature is valid, but the token was not issued to that client.
The fix separates and validation, requires proper and nonce, and uses the protocol library. The case shows that valid encryption does not replace context of use.
Case 2 - gateway authorizes, backend exposes object from another client
The gateway requires contas.read and forwards GET /contas/{id}. The backend searches for the ID without checking the link with the subject. An authenticated consumer changes the ID and reads another customer's account. The and are correct, but there is Broken Object Level .
The fix applies per-object in the domain and registers principal, tenant, and resource. The gateway continues validating token and , but does not attempt to infer ownership without reliable data.
Case 3 - secret shared between twenty applications
Twenty jobs use the same client_id and secret. After a leak, the organization needs to rotate everyone simultaneously and is unable to identify the person responsible for the traffic. The migration creates individual identity, owner, and quota per job, followed by revocation of the shared secret.
The gain is not just cryptographic. Individualization allows for least privilege, auditing, deprecation, and incident response on a per-consumer basis.
Lab 1 - validate claims from a synthetic
Generate a laboratory with , , exp and controlled.
Validate the signature with a local key and then change aud, exp and typ.
Confirm that each change is rejected by specific rule.
Only register synthetic headers and claims, never real production tokens.
Lab 2 - matrix
Model read, create, approve, and cancel operations.
List roles, attributes, relationships and necessary conditions.
Implement allow and deny cases with automated testing.
Include attempt to access object from another tenant.
Lab 3 - policy at the gateway
Configure an authorized gateway or simulator to require and .
Send tokens that are missing, expired, from another and without .
Compare 401 and 403 and record which layer responded.
Change the signing key and observe the caching and rotation behavior.
Lab 4 - inventory of workload identities
List service principals, managed identities, service accounts, and secrets for a lab environment.
Associate owner, resource, permissions and expiration.
Identify static credentials replaceable by or managed identity.
Define deactivation process and test revocation.
Chapter summary
Identity is the basis of access control, but it depends on registration, credentials, validation and life cycle. Identifier is not proof. establishes a principal under a given context; decides an action on a resource. , and audit complete the chain.
APIs can use API keys, Basic, sessions, opaque tokens, JWTs, mTLS and proofs of possession. Each mechanism has limits. Bearer tokens are reusable by whoever obtains them; sender-constrained tokens reduce replay. Signed is not encrypted and needs validation of , , time, type, algorithm and claims.
OAuth 2.0 handles delegated ; OpenID Connect adds for customers. , and refresh token have different recipients and purposes. can combine , , , and centralized policies, but domain and object rules remain the responsibility of the service.
API Gateways function as for cross-cutting controls and can validate tokens, certificates and keys. The architecture needs to preserve user and application identity, prevent forged headers, record the origin of the decision, and use short-lived workload identities. Effective security requires least privilege, rotation, observability, and deniability testing.
Next step of the course
Chapter 15 will delve deeper into Basic Auth, Digest and API Keys, analyzing transmission, HTTP challenges, secret storage, replay, rotation, application identification and limitations of these mechanisms in enterprise APIs.
Identity and access checklist
Each call can be associated with an individual principal and a known owner.
is separate from operation and object .
, , type, algorithm and time are explicitly validated.
and are not interchangeable.
API keys and secrets do not appear in URLs, logs or source code.
Application credentials have rotation and revision date.
Scopes, roles, permissions and attributes have documented semantics.
The gateway removes external identity headers before entering trusted context.
The backend applies fine-grained when it depends on state or ownership.
401 and 403 preserve semantics and do not reveal sensitive details.
Logs record principal, client, decision, resource, policy and correlation without tokens.
Workloads use short credentials or when possible.
Policies have positive and negative tests, versioning and rollback.
Inventory and shutdown process include grants, sessions, tokens, and certificates.
Exercises
Differentiate between subject, principal, identifier, and token.
Explain why strong does not fix Broken Object Level .
Compare , client secret, certificate and workload .
Explain why a valid signature is not enough to accept a .
Differentiate , and refresh token.
Model of a transfer using role, attributes and ownership.
Describe when 401, 403, and 404 can be used.
Explain the role of , , PIP and PAP.
Propose logs for a delegated call while preserving user and application.
Create migration plan from Basic to asymmetric or token.
List controls against replay.
Describe troubleshooting for token accepted at the gateway and rejected at the backend.
Glossary
Table 17 - Essential vocabulary of the chapter.
Term
Definition
ABAC
Authorization based on subject, resource, action and environment attributes.
Access token
Credential used by a client to access a resource server.
API key
Value associated with the consumer or plan; does not imply strong identity in and of itself.
Audience
Recipient to whom a token was issued.
Authentication
Process of validating proof linked to an identity.
Authorization
Decision on action permitted to a principal on which resource.
Bearer token
Token usable by whoever owns the value.
claim
Affirmation carried in token or assertion.
Credential
Material used to demonstrate control or identity linkage.
Delegation
Limited concession to act on behalf of another subject.
Federation
Acceptance of identities or assertions from another trusted domain.
ID token
OpenID Connect token intended for the client to communicate authentication.
Issuer
Entity that issues and signs the token or assertion.
JWT
Compact format for claims protected by JWS or JWE.
PDP
Component that evaluates policy and produces decision.
PEP
Component that applies the decision to access.
Main
Operational representation of an identity in the system.
RBAC
Role-based authorization.
ReBAC
Relationship-based authorization.
Scope
Delegated authority expressed for an access token.
Sender-constrained token
Token tied to proof of a client key.
Workload identity
Non-human identity assigned to running software.
Annex A - Mechanism choice matrix
Table 18 - The final choice depends on risk, consumers and infrastructure.
Scenario
Starting mechanism
Additional controls
Low-risk public API with quota
API key
TLS, rotation, rate limiting and monitoring.
Controlled legacy integration
Basic temporary
individual credential, TLS, vault and migration plan.
User in web application
OIDC + session or tokens
MFA, CSRF/XSS, audience and object authorization.
Service to service
client credentials, mTLS or federation
minimum scope, audience, rotation and owner.
Workload in Azure
managed identity
Minimal RBAC and sign-in logs.
Multi-cloud workload/Kubernetes
workload federation or SPIFFE
specific trust, short credential and attestation.
High-risk API
sender-constrained token + contextual policy
mTLS/DPoP, step-up, detection and enhanced auditing.
OpenID Foundation. OpenID Connect Core 1.0, Second Errata Set.
NIST. SP 800-63-4 - Digital Identity Guidelines. 2025.
NIST. SP 800-63B-4 - and Authenticator Management. 2025.
NIST. SP 800-207 - Zero Trust Architecture. 2020.
SPIFFE. SPIFFE Concepts, Workload API and SVID Specifications.
Microsoft Learn. Microsoft Enter workload identities and managed identities.
Microsoft Learn. Azure API Management validate- and validate-azure-ad-token policies.
Axway Documentation. OAuth 2.0, OpenID Connect and verification on API Gateway.
OWASP. API Security Top 10 - 2023 Edition.
Update note
Protocols, libraries, products, and identity policies evolve. Before implementing any flow or policy, validate the current specifications, product version and behavior in an authorized environment.