In this lesson, you will learn how to define and implement application-specific permission sets that extend the base OAuth2 specification to provide granular control over your API resources.
Why Custom Scopes?
Standard OAuth2 scopes—like openid or profile—are useful for generic identity information, but they often lack the nuance required for complex applications. When your API handles distinct business logic (e.g., reports:generate vs. reports:view), you need custom scopes. These act as "permission gates" that your resource server checks before allowing an action.
Defining Scopes in Your Strategy
When building a custom scope, you aren't just adding a string to a token; you are creating a contract between the Authorization Server and your Resource Server. In a Node.js environment, this typically involves mapping an incoming token's scope claim to specific controller functions.
Consider an express middleware that validates these custom strings:
const authorize = (requiredScope) => {
return (req, res, next) => {
const scopes = req.user.scope.split(' ');
if (scopes.includes(requiredScope)) {
return next();
}
res.status(403).json({ error: 'Insufficient scope permissions' });
};
};
// Usage
app.post('/reports', authorize('reports:generate'), (req, res) => {
// Logic to generate a sensitive report
});
Implementing Granularity
To manage these effectively, keep your scope definitions descriptive and hierarchical. A well-designed scope uses a resource:action naming convention. By strictly validating these strings at the edge of your service, you ensure that even if an access token is compromised, the damage is restricted to the specific, narrow permissions granted by that scope.
As you define these, remember to document them thoroughly so developers consuming your API understand exactly what privilege each scope confers. While the OAuth2 specification provides the mechanism for transport, the definition of these scopes is your responsibility as an architect to ensure your system adheres to the Principle of Least Privilege.
Key Takeaway: Custom OAuth scopes allow you to enforce granular, resource-specific access control by translating business-level requirements into verifiable strings embedded within the identity token.