OAuth 2.0 Scope Management Best Practices
How to design, request, and validate OAuth 2.0 scopes for fine-grained access control. Includes common scope patterns from popular APIs.
Detailed Explanation
OAuth 2.0 Scope Management
Scopes define the boundaries of access that a client can request. They are the primary mechanism for limiting what an OAuth 2.0 access token can do. Good scope design is essential for security (principle of least privilege) and for user trust (users can see exactly what they are granting).
How Scopes Work
- Client requests scopes in the authorization request:
scope=read:user write:repos - User reviews and consents to the requested permissions
- Server may grant fewer scopes than requested (never more)
- Token includes granted scopes in the response:
"scope": "read:user write:repos" - Resource server enforces scope requirements per endpoint
Common Scope Patterns
Flat scopes (simple):
read write delete admin
Resource-based scopes (GitHub style):
read:user write:repos delete:gists admin:org
Hierarchical scopes (Google style):
https://www.googleapis.com/auth/gmail.readonly
https://www.googleapis.com/auth/gmail.send
https://www.googleapis.com/auth/calendar.events
OpenID Connect standard scopes:
| Scope | Claims Included |
|---|---|
openid |
Subject identifier (required for OIDC) |
profile |
name, family_name, given_name, picture, etc. |
email |
email, email_verified |
address |
Postal address |
phone |
phone_number, phone_number_verified |
Scope Validation on the Resource Server
function requireScope(requiredScope) {
return (req, res, next) => {
const tokenScopes = req.token.scope.split(" ");
if (!tokenScopes.includes(requiredScope)) {
return res.status(403).json({
error: "insufficient_scope",
error_description: `Required scope: ${requiredScope}`,
});
}
next();
};
}
// Usage
app.get("/api/user", requireScope("read:user"), getUserHandler);
app.post("/api/repos", requireScope("write:repos"), createRepoHandler);
Best Practices
- Request only the scopes you actually need (least privilege)
- Use granular scopes rather than broad ones (prefer
read:useroveradmin) - Document all available scopes in your API reference
- Handle scope downgrade gracefully (the server may grant fewer scopes)
- Re-request additional scopes incrementally when needed (progressive consent)
Use Case
Designing an API that uses OAuth 2.0. You need to define meaningful scopes that map to your API's resources and operations, and implement scope checking middleware in your resource server to enforce access control.