How toUse `scope` to Authorize Actions in Your API
When using OAuth2 with access tokens, one of the most important claims is scope
.
The scope
claim defines what the token is allowed to do. Each scope represents a permission—like contacts.read
, contacts.write
, or calendar.edit
.
Instead of relying on roles or user types, scopes give you a more granular way to control access in your API.
Example: Enforcing contacts.read
scope
If your API receives a JWT, you can use the scope
claim to check if the client has permission to access a specific resource:
if (!jwt.scope?.includes("contacts.read")) {
throw new AuthorizationError("Missing required scope");
}
This is especially important when tokens can carry multiple scopes. A token may have:
{
"scope": "contacts.read contacts.write calendar.read";
}
Only the scopes explicitly granted should be honored.
By checking for required scopes on each protected route, your API follows the principle of least privilege and avoids unauthorized access.
I'm currently writing a book called React Router OAuth2 Handbook, focused on implementing secure OAuth2 authentication in Remix and React Router apps—using patterns you can apply to any web app.
The landing page is live (book coming soon) at books.sergiodxa.com