Technical docs
Securing APIs with scopes & claims
A practical guide to how OAuth 2.0 scopes and JWT claims work together to protect backend APIs — covering authorization flows, token validation, and enforcement patterns.
Overview
Modern applications are composed of client apps (web, mobile, SPA) that call backend APIs. To ensure only authorized clients and users can access specific resources, we rely on two complementary mechanisms built into the OAuth 2.0 and OpenID Connect (OIDC) standards:
Scopes
Define what a client application is allowed to do. They represent permissions requested against a resource server (your API).
Claims
Carry who the user or client is. Structured as key-value pairs inside a JWT token, they convey identity, roles, and contextual data to your API.
Together, scopes and claims allow an API to answer two fundamental security questions: "Is this client allowed to call this endpoint?" (scope) and "Does this user have the right to access this specific data?" (claims).
The Token Flow
Before a client can call a protected API, it must obtain an access token from an authorization server (e.g., Azure AD, Auth0, Okta, Keycloak). The flow looks like this:
- The client requests an access token, specifying desired scopes.
- The user authenticates and consents (for delegated flows).
- The authorization server issues a signed JWT access token containing granted scopes and identity claims.
- The client sends the token as a
Bearertoken in theAuthorizationheader. - The API validates the token signature, expiry, audience, scopes, and claims before serving the request.
GET /api/orders HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...Scopes
Scopes are strings that represent a permission — either a broad category of access or a fine-grained operation on a resource. They are agreed upon between the client, the authorization server, and the API.
Requesting Scopes
Scopes are requested in the OAuth authorization request and in client credential flows:
// Authorization Code Flow (user sign-in)
GET https://login.example.com/authorize
?response_type=code
&client_id=my-spa-client
&scope=openid profile email api://my-api/orders.read api://my-api/orders.write
&redirect_uri=https://app.example.com/callback
// Client Credentials Flow (service-to-service)
POST https://login.example.com/token
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials
&client_id=my-service
&client_secret=...
&scope=api://my-api/.defaultScope Design Patterns
Well-designed scopes follow a consistent naming convention and granularity:
| Scope | Pattern | Description |
|---|---|---|
| orders.read | resource.action | Read access to orders |
| orders.write | resource.action | Create and update orders |
| orders.delete | resource.action | Delete orders (elevated) |
| admin | role-like | Broad administrative access |
| api://my-api/.default | Azure AD app-level | All permissions the app has been granted |
| openid | OIDC standard | Issue an ID token (identity) |
| profile | OIDC standard | Include name/picture in ID token |
| OIDC standard | Include email address in ID token |
Principle of Least Privilege
admin should be reserved for privileged back-office services, not public client apps.Claims
Claims are assertions about the subject (user or client) embedded as key-value pairs inside a JSON Web Token (JWT). They are cryptographically signed by the authorization server so that resource servers can trust them without calling back.
Standard JWT Claims (RFC 7519)
| Claim | Full Name | Purpose |
|---|---|---|
| sub | Subject | Unique identifier of the user or principal |
| iss | Issuer | URL of the authorization server that issued the token |
| aud | Audience | Intended recipient(s) — your API must verify this |
| exp | Expiration | Unix timestamp after which the token is invalid |
| iat | Issued At | Unix timestamp when the token was issued |
| nbf | Not Before | Token is not valid before this timestamp |
| jti | JWT ID | Unique identifier for replay detection |
Common Identity Claims (OIDC / Azure AD)
Identity providers add their own claims to access and ID tokens:
// Decoded JWT access token payload (Azure AD example)
{
"iss": "https://login.microsoftonline.com/{tenant-id}/v2.0",
"sub": "AadOid|00000000-0000-0000-0000-000000000001",
"aud": "api://my-api",
"exp": 1712520000,
"iat": 1712516400,
"nbf": 1712516400,
// User identity
"oid": "00000000-0000-0000-0000-000000000001", // Immutable user object ID
"tid": "11111111-1111-1111-1111-111111111111", // Azure AD tenant ID
"upn": "michael@example.com",
"name": "Michael Wolfgang",
"email": "michael@example.com",
// Authorization
"scp": "orders.read orders.write", // Delegated scopes (space-separated)
"roles": ["Orders.Manager", "Reports.Viewer"], // App role assignments
// Client info
"azp": "client-app-id", // Authorized party (client that requested token)
"appid": "your-api-app-id"
}The scp Claim vs the roles Claim
Two claims are especially important for API authorization and are often confused:
scp (or scope)
Delegated permissions — what the user has consented to let the app do on their behalf. Only present in delegated (user + app) token flows.
Delegated Flow Onlyroles
Application roles — permissions assigned to the app or user in the directory. Present in both delegated and client credentials flows.
Delegated & App-OnlyValidating Tokens in a Backend API
Every API endpoint that requires authentication must independently validate the incoming token. Never trust a token that has been forwarded without re-validation. The validation steps are:
Step 1 — Verify the Signature
The JWT is signed with the authorization server's private key. Fetch the public signing keys from the well-known JWKS endpoint and verify the signature.
// Node.js / Express example using 'jose' library
import { createRemoteJWKSet, jwtVerify } from 'jose';
const JWKS = createRemoteJWKSet(
new URL('https://login.microsoftonline.com/{tenant-id}/discovery/v2.0/keys')
);
async function verifyToken(authHeader) {
const token = authHeader?.replace('Bearer ', '');
if (!token) throw new Error('Missing token');
const { payload } = await jwtVerify(token, JWKS, {
issuer: 'https://login.microsoftonline.com/{tenant-id}/v2.0',
audience: 'api://my-api',
});
return payload; // Returns decoded, verified claims object
}Step 2 — Validate Standard Claims
After signature verification, check the token's metadata claims:
function validateStandardClaims(claims) {
const now = Math.floor(Date.now() / 1000);
if (claims.exp < now)
throw new Error('Token has expired');
if (claims.nbf && claims.nbf > now)
throw new Error('Token not yet valid');
if (claims.aud !== 'api://my-api')
throw new Error('Invalid audience — token not intended for this API');
if (claims.iss !== 'https://login.microsoftonline.com/{tenant-id}/v2.0')
throw new Error('Invalid issuer');
}Always verify the audience (aud)
Step 3 — Enforce Scopes
Check that the token contains the required scope before processing the request:
// Middleware: require a specific scope
function requireScope(requiredScope) {
return (req, res, next) => {
const claims = req.claims; // Attached by token verification middleware
const scopes = (claims.scp || claims.scope || '').split(' ');
if (!scopes.includes(requiredScope)) {
return res.status(403).json({
error: 'insufficient_scope',
message: `Required scope: ${requiredScope}`,
});
}
next();
};
}
// Usage on routes
app.get('/api/orders', requireScope('orders.read'), getOrders);
app.post('/api/orders', requireScope('orders.write'), createOrder);
app.delete('/api/orders/:id', requireScope('orders.delete'), deleteOrder);Step 4 — Enforce Claims-Based Authorization
Scopes confirm what the client can do; claims confirm what data the user can touch. Use claims for fine-grained row-level and resource-level access control:
// Only return orders belonging to the authenticated user
app.get('/api/orders', requireScope('orders.read'), async (req, res) => {
const { sub, oid, roles } = req.claims;
// Admins see all orders; regular users see only their own
const filter = roles?.includes('Orders.Manager')
? {} // No filter — full access
: { ownerId: oid }; // Scoped to their user object ID
const orders = await db.orders.findMany({ where: filter });
res.json(orders);
});
// Verify the caller owns the resource before returning it
app.get('/api/orders/:id', requireScope('orders.read'), async (req, res) => {
const order = await db.orders.findById(req.params.id);
if (!order) return res.status(404).json({ error: 'Not found' });
// Claim-based ownership check
const isOwner = order.ownerId === req.claims.oid;
const isAdmin = req.claims.roles?.includes('Orders.Manager');
if (!isOwner && !isAdmin)
return res.status(403).json({ error: 'Access denied' });
res.json(order);
});ASP.NET Core Example
The same pattern in C# using the Microsoft.Identity.Web library:
// Program.cs — configure JWT bearer authentication
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));
builder.Services.AddAuthorization(options => {
options.AddPolicy("OrdersRead", p => p.RequireClaim("scp", "orders.read"));
options.AddPolicy("OrdersWrite", p => p.RequireClaim("scp", "orders.write"));
options.AddPolicy("AdminOnly", p => p.RequireRole("Orders.Manager"));
});
// OrdersController.cs
[ApiController]
[Route("api/[controller]")]
[Authorize]
public class OrdersController : ControllerBase
{
[HttpGet]
[Authorize(Policy = "OrdersRead")]
public async Task<IActionResult> GetOrders()
{
var userId = User.FindFirstValue("oid"); // Read the oid claim
var isAdmin = User.IsInRole("Orders.Manager");
var orders = isAdmin
? await _repo.GetAllOrders()
: await _repo.GetOrdersByOwner(userId);
return Ok(orders);
}
}Service-to-Service (App-Only) Tokens
When a backend service calls another API without a user in the loop (daemon services, background workers, microservices), use the Client Credentials flow. These tokens carry roles instead of scp.
// Detecting app-only vs delegated token
function isAppOnlyToken(claims) {
// Delegated tokens have a non-zero 'scp' and a real 'sub'
// App-only tokens have no 'scp' and 'sub' equals the application's object ID
return !claims.scp && claims.idtyp === 'app';
}
app.get('/api/internal/reports', async (req, res) => {
const claims = req.claims;
if (isAppOnlyToken(claims)) {
// App-only: check app roles
if (!claims.roles?.includes('Reports.Viewer'))
return res.status(403).json({ error: 'App role required' });
} else {
// Delegated: check scope AND user identity
requireScope('orders.read')(req, res, () => {});
}
// handle request ...
});Best Practices
🔒 Always validate on the API
🎯 Validate the audience
⚡ Keep tokens short-lived
🔑 Least privilege scopes
📋 Prefer immutable claims
🚫 Never trust without verification
📝 Log for auditability
🔄 Rotate signing keys
Common Pitfalls
- ✗Skipping audience validation→Always verify aud matches your API client ID / app URI.
- ✗Checking scopes client-side only→The API must re-validate every token — the client can be compromised.
- ✗Using the ID token to call APIs→ID tokens are for identity; use the access token for API authorization.
- ✗Storing tokens in localStorage→Use HttpOnly cookies or in-memory storage; localStorage is readable by any script.
- ✗Long-lived access tokens→Short expiry + refresh tokens is safer than long-lived tokens.
- ✗Ignoring the nbf claim→Validate not-before to prevent replay of pre-issued tokens.
- ✗Hardcoding public keys→Always fetch keys dynamically from the JWKS endpoint to support key rotation.
- ✗Roles defined only in the token, not the directory→App roles assigned in the authorization server / directory are authoritative; do not let users self-assign roles via token manipulation.
Further Reading
- ›OAuth 2.0 Framework(RFC 6749)
- ›JSON Web Token (JWT)(RFC 7519)
- ›OpenID Connect Core(openid.net)
- ›Microsoft Identity Platform(Microsoft Learn)
- ›OWASP API Security Top 10(owasp.org)
- ›OAuth 2.0 Security Best Current Practice(RFC Draft)
Tip: paste a token into the JWT Decoder to inspect the claims described above.