Internal Api

Credentials for Internal API Access

Learn how credentials authenticate internal API clients, how IAM authorization works, and how to issue, store, rotate, revoke, monitor, and respond to exposed credentials safely.

Credentials are the evidence a client presents to prove its identity to an internal API. A credential may be a secret, signed artifact, certificate, or identity assertion. The client can be a human user, application, service account, CI/CD job, or other workload.

An internal API is not automatically safe merely because it is reachable only from a private network. Credentials provide service isolation, support auditing, reduce accidental access, and help prevent unauthorized callers from reaching sensitive operations.

Authentication and Authorization

Authentication is the verification of identity. It answers, “Who is calling?” A credential is used during this step.

Authorization is the evaluation of whether an authenticated identity may perform a particular action. IAM policies, roles, groups, scopes, and resource permissions determine the answer.

For example, an access token can be valid and correctly signed, so authentication succeeds. The same token may still receive 403 Forbidden because its principal lacks permission to update a resource. Conversely, a missing, expired, or incorrectly targeted token normally causes 401 Unauthorized.

The identity recognized by IAM is called a principal. A principal may be a user, service account, application, workload, or another recognized identity.

  • Credentials establish or assert the principal's identity.
  • IAM maps that principal to roles, groups, policies, scopes, and resource permissions.
  • The API checks both credential validity and permission for the requested endpoint and operation.

Credential Types

Choose the narrowest credential type that meets the integration's needs. In general, short-lived credentials issued automatically for a specific audience are safer than long-lived static secrets.

Credential typeTypical callerLifetimeHow it is presentedRecommended useKey risks and restrictions
API keySimple applications, command-line tools, low-risk integrationsDays to months, sometimes longerApproved API-key headerIdentification and limited access where the platform specifically supports itStatic values are easy to copy; usually weaker than scoped, short-lived tokens; never put one in a URL
Client IDRegistered applications, including interactive clientsUsually long-lived public identifierClient authentication or authorization request parameterIdentifying an application; it is not a secret by itselfDoes not prove possession of a confidential secret
Client secretServer-side applications and automationShort or moderate lifetime with planned rotationApproved client-authentication flowAuthenticating a confidential application to obtain tokensMust not be embedded in browser code, mobile binaries, repositories, or distributed configuration
Bearer access tokenServices, command-line tools, applicationsTypically minutes to about an hourAuthorization: Bearer ...Calling an API with specific audience and scopesAnyone possessing it can usually use it until expiry or revocation; protect it like a secret
Refresh tokenServer-side applications and user-facing applications using an interactive sign-in flowDays to months, subject to policySubmitted only to the token serviceObtaining new access tokens without repeating interactive authenticationMore sensitive and longer-lived than an access token; do not send it to the resource API
Signed service-account assertionMachine-to-machine services and automationUsually minutesExchanged with an identity provider for an access tokenProving possession of a service identity without distributing a reusable API secretSigning keys require strict protection, rotation, and clock management
mTLS certificateHigh-trust server-to-server servicesWeeks to monthsDuring the TLS client-certificate handshakeMutual authentication where both client and server verify certificatesPrivate keys must be protected; certificate renewal and trust-chain management are operational requirements
Workload identity tokenCloud workloads, containers, jobs, and CI/CD systemsTypically minutes to an hourObtained by an identity exchange and sent as a bearer access token or equivalent assertionAutomatically issued credentials without a stored long-lived secretTrust configuration must prevent an unrelated workload from impersonating the identity

Choosing for Common Callers

  • Human users: Prefer an interactive identity-provider flow that produces short-lived access tokens. Do not ask users to share service secrets.
  • Server-side applications: Use a service account or application identity with workload identity, a signed assertion, or a confidential client flow.
  • Command-line tooling: Use interactive sign-in and short-lived tokens when possible. A narrowly scoped API key may be acceptable for approved low-risk tooling, but it requires an owner and expiry.
  • CI/CD systems: Use an automation-specific identity or workload identity. If a bootstrap secret is unavoidable, keep it in the pipeline's protected secret facility.
  • Machine-to-machine services: Prefer workload identity, signed assertions, short-lived access tokens, or mTLS over shared employee credentials.

A client ID is generally public application metadata. A client secret, private key, refresh token, API key, and access token are confidential unless the platform explicitly says otherwise.

Credential Issuance and Ownership

Credential creation should occur through an approved IAM system, identity provider, developer portal, or administrative process. The requester, approver, and operator may be different people, especially for production access.

Every credential record should have:

  • A named human owner responsible for its lifecycle.
  • An application, service account, or workload identity that uses it.
  • A clear purpose and the internal API operations required.
  • An environment, such as development, test, staging, or production.
  • An expiration date or a documented review date.
  • An approving team or system and a contact for incident response.

For non-human integrations, the service account or application identity should be the principal owner. An employee may be accountable for that identity, but the integration should not depend on that employee's personal credential.

Keep environments separate. A development token must not access production resources, and a production service account must not be reused by test jobs. Separate identities make policy review, audit interpretation, and emergency revocation safer.

Obtaining Credentials

  1. Register the application, service, or workload with the approved IAM or identity platform.
  2. Describe the API audience, required operations, scopes, environments, and expected calling pattern.
  3. For an interactive OAuth-style client, register exact redirect URIs. Avoid broad wildcard redirects.
  4. Specify the intended audience so issued tokens are accepted only by the correct API.
  5. Request the minimum scopes and resource permissions required.
  6. Obtain approval according to the environment's access policy.
  7. Generate or issue the credential through the approved system.
  8. Save a newly displayed secret immediately in the approved secret manager or protected CI/CD secret facility.

Many systems display a client secret or private value only once. If it is lost, create a replacement rather than requesting that a secret be sent through chat, email, or a ticket.

Using Credentials with API Requests

Bearer Access Tokens

A common pattern is to request a short-lived access token from an identity provider and send it to the API in the Authorization header over TLS.

GET /internal/resource HTTP/1.1
Host: api.internal.example
Authorization: Bearer <short-lived-access-token>

A bearer token is called “bearer” because possession is normally sufficient to present it. Do not expose it in diagnostics, application responses, URLs, browser code, or logs.

Token formats vary. A token may be an opaque string or a signed structure containing claims. At a conceptual level, the API or its gateway validates:

  • Issuer: the trusted identity provider that created or signed the token.
  • Audience: the intended recipient API or service.
  • Expiry: the time after which the token is no longer accepted.
  • Signature: evidence that the token was issued by a trusted signer and was not altered.
  • Scopes or claims: requested or granted permissions and identity information.

An access token is presented to the resource API. A refresh token is used with the token service to obtain a new access token and should not be sent to the internal API. Refresh tokens require stronger protection because they often live longer.

Other Presentation Methods

  • An API key goes in the exact approved API-key header, not in a query string.
  • A client ID and client secret are used in an approved token-acquisition flow; they are not substitutes for API authorization.
  • With mTLS, the client proves possession of a private key during the TLS handshake, while the server validates the client certificate against an approved trust configuration.
  • With workload identity, the workload obtains an assertion or token from an identity system and exchanges it for an access token targeted at the internal API.
identity = obtain_workload_identity()
token = request_access_token(identity,
    audience=<internal-api-audience>,
    scopes=[<required-scope>])
call_api(authorization='Bearer ' + token)

Send credentials only over HTTPS/TLS. Never place confidential credentials in URLs, source code, distributed configuration files, error reports, tickets, chat messages, or client-side browser code.

Authorization Relationship

After authentication, the API maps the principal to IAM objects such as a service account, role, group, policy, scope, or resource-level permission. The resulting decision should be limited to the requested operation and resource.

A valid credential is not automatically authorized for every endpoint. For example, a service may possess a valid token for the correct API audience but have only read scope. A write request should still be denied.

  • Use separate identities for unrelated services and environments.
  • Grant only the operations and resources required by the integration.
  • Prefer narrowly defined roles over broad administrator permissions.
  • Review permissions when an application changes, an owner changes, or a deployment target changes.
  • Do not solve a 403 response by granting excessive permissions without first identifying the missing authorization rule.

Credential Storage and Secret Handling

Use an approved secret manager: a protected system that stores secret values, controls access, records audit events, and supports masking and rotation. A protected runtime environment or CI/CD secret facility may also be appropriate.

Storage methodAppropriate useAdvantagesLimitationsSecurity requirements
Secret managerProduction secrets, client secrets, API keys, private keys, refresh tokensCentral access control, encryption at rest, audit trails, rotation support, maskingRequires integration and availability planningRestrict read access, use workload identity, audit retrieval, and avoid displaying values
Protected CI/CD secret facilityPipeline-only bootstrap values and deployment credentialsIntegrates with jobs and masks many values automaticallyValues may still leak through unsafe commands or artifactsLimit job scope, mask output, prevent fork exposure, and rotate on ownership changes
Runtime environment variableDelivery of a secret reference or short-lived value to a processSeparates deployment configuration from source codeMay appear in diagnostics, crash reports, process inspection, or child-process environmentsUse only through an approved runtime, restrict host access, and never print the value
Local developer credential storeInteractive development and command-line useSupports user-specific sign-in without shared secretsLocal devices may be compromised or misconfiguredUse short-lived credentials, device protection, and separate development permissions
Source repository or distributed configuration fileNon-secret references onlyEasy to distributeNot suitable for confidential values; history and copies persistStore references, not secrets; enable secret scanning and review controls

Environment variables are a delivery mechanism, not a complete security boundary. Process inspection, diagnostic endpoints, debug dumps, and accidental logging can expose them. Prefer a runtime integration that retrieves a secret only when needed and keeps it masked.

INTERNAL_API_TOKEN=<injected-at-runtime>
INTERNAL_API_BASE_URL=https://api.internal.example
credentials:
  tokenSecretRef: <approved-secret-manager-reference>
  audience: <internal-api-audience>
  • Encrypt secrets at rest and use TLS while transmitting them.
  • Restrict secret retrieval to the exact workload, environment, and operation that need it.
  • Record access and changes in audit trails without recording secret values.
  • Mask tokens and secrets in logs, pipeline output, traces, and support tooling.
  • Never commit secrets to repositories or embed them in software distributed to users.
  • Never share secret values in tickets, chat, email, screenshots, or error reports.

Expiration, Rotation, and Revocation

Expiration is planned invalidation at a specified time. Rotation replaces a credential on a planned or emergency basis. Revocation invalidates a credential before its normal expiry.

Set lifetimes according to risk and capability. Short-lived access tokens should normally expire quickly. Longer-lived client secrets, API keys, refresh tokens, certificates, and signing keys require an owner, review schedule, monitoring, and a tested replacement procedure.

Safe Rotation Without Downtime

  1. Create the replacement credential while the current credential remains active.
  2. Store the replacement in the approved secret-delivery system.
  3. Update the consuming application or pipeline.
  4. Deploy or reload the configuration through the normal change process.
  5. Verify successful authentication and the expected authorization with the replacement.
  6. Confirm all consumers have migrated using deployment status and audit records.
  7. Revoke or retire the old credential.
  8. Monitor for continued attempts using the retired credential.

Design dependent services to renew tokens before expiry, retry token acquisition safely, and reload rotated secrets without an outage where possible. Do not retry indefinitely with an expired or revoked credential. If a client caches a credential, define how its cache is refreshed and how quickly a new value becomes active.

Revoke immediately when compromise is suspected, an owner or personnel relationship changes, an application is abandoned, or an environment is decommissioned. Remove unused credentials instead of allowing them to remain valid until an uncertain future expiry date.

Lifecycle stageOwner actionAdministrative or platform actionAudit evidenceExpected outcome
RequestDocument purpose, principal, environment, scopes, and expiryReview requester and riskRequest and approval recordsTraceable, justified access
IssueConfirm the credential is for the named application or workloadGenerate with approved policyIssuance event and credential metadataCredential exists with an accountable owner
Store and deploySave once in the approved facility and update the consumerEnforce access controls and maskingSecret retrieval and deployment recordsOnly the intended runtime can use it
Use and monitorReview usage and report anomaliesLog principal, endpoint, result, and policy decisionsAccess and failed-authentication eventsExpected access is observable
RotateTest the replacement and migrate every consumerIssue replacement and preserve overlap temporarilyRotation and deployment eventsContinuous access with reduced secret age
Expire or revokeStop use and confirm dependent systems are updatedDisable credential and remove unused permissionsExpiry or revocation eventCredential can no longer authenticate

Auditing and Monitoring

Record credential issuance, use, rotation, failed authentication, policy changes, and revocation. Audit records should identify the principal, application, workload, environment, endpoint, decision, and time. They must not expose the credential value, full authorization header, private key, or refresh token.

Useful detection signals include:

  • Requests from unusual locations, hosts, networks, or deployment environments.
  • Tokens with an unexpected audience or issuer.
  • Repeated authentication failures or rapid changes in failure rate.
  • Unexpectedly high request volume or unusual endpoint access.
  • Use after scheduled expiration, retirement, or application decommissioning.
  • Policy changes that grant broader access than the service normally requires.

Correlate audit records with deployment records and service ownership. Monitoring should alert on suspicious behavior without causing the monitoring system itself to capture secret material.

Incident Response for Exposed Credentials

Assume an exposed credential is compromised. Deleting the visible text is not sufficient: copies may remain in repository history, logs, caches, build artifacts, container layers, backups, or deployment outputs.

  1. Revoke or disable: Stop the exposed credential immediately, especially if it grants production access.
  2. Replace: Create a new credential with the minimum required permissions and store it safely.
  3. Update affected systems: Deploy the replacement through the approved secret-delivery path.
  4. Identify exposure: Determine where the value appeared and which systems, environments, or artifacts may contain it.
  5. Inspect audit logs: Search for use during the exposure period, including unusual locations, audiences, operations, and volume.
  6. Remediate sources: Remove the value from active code, configuration, logs, artifacts, and accessible histories according to the organization's response process.
  7. Improve controls: Add secret scanning, log masking, protected variables, review checks, and safer identity delivery where appropriate.
  8. Document: Record the timeline, affected principal, actions, evidence, impact assessment, and preventive changes.

Practical Examples

Backend Service Calling an Internal API

Assign the backend a dedicated service account or workload identity. Have the workload request a short-lived access token for the internal API's audience and only the read or write scopes it needs. Send the token in the authorization header over TLS. Do not use an employee's personal token or a shared organization-wide API key.

CI/CD Deployment Automation

Give the pipeline an automation-specific identity restricted to deployment operations in its target environment. Store any unavoidable bootstrap secret in the pipeline's protected secret facility. Prevent untrusted jobs, pull requests, and forks from reading the value. Rotate it when pipeline ownership, deployment tooling, or the target environment changes.

Credential Rotation Without Downtime

Create a replacement while the old credential remains valid, update the application's secret reference, deploy the change, and verify successful calls using the new value. After every consumer has migrated, revoke the old credential and watch audit events for continued use.

Accidentally Committed Secret

Treat the secret as compromised immediately. Revoke it, create a replacement, and update consumers. Remove it from active code and configuration, then inspect repository history, build logs, deployment outputs, caches, and artifacts. Review audit events for use during the exposure period. Removing the latest copy alone does not invalidate the old value.

Authentication Failure Guide

Symptom or responseLikely causeHow to verifyCorrective action
401 UnauthorizedMissing header, malformed credential, expired token, untrusted issuer, or wrong audienceCheck the approved header format without printing token contents; inspect safe token metadata and server audit dataObtain a fresh token, confirm system time, and match issuer and audience to the API registration
403 Forbidden after authentication succeedsPrincipal lacks the required role, scope, or resource permission, or belongs to the wrong environmentIdentify the principal from safe audit data and review the applicable IAM decisionApply the minimum necessary IAM change and confirm the environment-specific identity is being used
Works locally but fails in deploymentSecret was not injected, deployed workload has a different identity, or network, certificate, or identity-provider access differsCheck secret and identity bindings and masked runtime logsCorrect deployment bindings, validate workload identity permissions, and verify trusted network paths
Requests fail after a scheduled dateCredential expired or rotation was incomplete; an old value remains in a consumerCheck expiry metadata and audit attempts by the retired credentialDeploy the replacement to every consumer and remove the expired value
Secret appears in source control or logsHard-coded configuration, unsafe debugging, or an unmasked CI/CD variableSearch active and historical sources, logs, artifacts, and audit eventsRevoke immediately, replace through the secret manager, remediate exposure, and add scanning and masking controls

Exam-Relevant Notes

  • Authentication answers who the caller is; authorization answers what that identity may do.
  • A valid credential can still be unauthorized for a particular endpoint, operation, scope, or resource.
  • Service accounts and workload identities are preferred for non-human integrations.
  • Short-lived, automatically issued tokens are generally safer than long-lived static secrets.
  • Access tokens go to the API; refresh tokens go to the token service.
  • Credentials must use TLS and must not appear in URLs, source code, logs, tickets, chat, or browser code when confidential.
  • Rotation should use overlapping credentials, validation, consumer migration, and retirement of the old value.
  • Suspected exposure requires revocation and replacement, not merely deletion of the visible text.