OAuth scopes
Declare your scopes once, gate a rule on one with .requires_scope(...) — the refusal is an RFC 6750 insufficient_scope challenge naming what to request.
A user hands an MCP client a token. It should be able to read their posts and nothing else — not because of who they are (they are an admin) but because of what this token was delegated.
Roles and scopes answer different questions, and both have to hold:
- Roles say who the caller is. They come from your identity model and drive the conditions in policies.
- Scopes say how much of that identity this particular token may
exercise. They only ever narrow — an admin token minted without
posts:writecannot write posts.
Declare the scope on the rule it conditions
Section titled “Declare the scope on the rule it conditions”A scope is a nest_rs::guards::Scope, declared once as a constant — the
token RFC 6749 §3.3 defines, checked against its grammar when it compiles:
use nest_rs::guards::Scope;
pub const POSTS_READ: Scope = Scope::new("posts:read");pub const POSTS_WRITE: Scope = Scope::new("posts:write");pub const AUDIO_TRANSCODE: Scope = Scope::new("audio:transcode");
pub const ALL: [Scope; 3] = [POSTS_READ, POSTS_WRITE, AUDIO_TRANSCODE];A rule requires one by name, so a scope no declaration holds does not
compile — requires_scope takes a Scope, never a string:
impl AbilityFactory for AuthzAbility { type Actor = Claims;
fn define(&self, actor: &Claims, ab: &mut AbilityBuilder) { ab.can(Action::Read, post::Entity) .when(|p| p.eq(post::Column::OrgId, actor.org_id)) .requires_scope(POSTS_READ);
ab.can(Action::Manage, post::Entity) .when(|p| p.eq(post::Column::OrgId, actor.org_id)) .requires_scope(POSTS_WRITE); }}That is the whole declaration. When the caller’s token does not carry the scope, the grant is withheld — not added at all. Every layer then refuses together, exactly as it would for a grant you never wrote: the class gate says no, the query pre-filter matches nothing, and the wire row holds nothing to expose.
Call it more than once to require all the named scopes. Scopes are
opaque tokens compared exactly (RFC 6749 §3.3) — posts:* is a value
you may mint, never a pattern the framework expands.
Tell the framework what the token carries
Section titled “Tell the framework what the token carries”Scopes reach the ability layer from the principal. Mark the field that
holds them #[principal(scopes)] on your claims type, and read the
standard space-delimited scope claim with the serde helper the
framework ships:
#[derive(Debug, Clone, Serialize, Deserialize, PrincipalIdentity)]pub struct Claims { #[principal(actor)] pub sub: Subject, pub client_id: String, #[principal(tenant)] pub org_id: Uuid, pub roles: Vec<Role>, #[principal(scopes)] #[serde( default, rename = "scope", with = "nest_rs::authn::scope::space_delimited", skip_serializing_if = "Vec::is_empty" )] pub scopes: Vec<String>,}The field is a list, never an Option: a token sent without its scope
claim reads as one granted nothing, and the derive refuses an optional
list at compile time.
The authentication guard publishes the result and the ability guard reads it. You write nothing else.
Grant no more than was registered
Section titled “Grant no more than was registered”Scopes only narrow if the issuer never hands out more than a client may
hold. nest_rs::oauth::server holds that rule for every token endpoint built
on it: the client ClientAuthenticationGuard attached reads its grant with
AuthenticatedClient::scope_for, which follows RFC 6749 §3.3 strictly — a
request naming scopes gets exactly those when every one is registered for the
client, a request naming one that is not gets invalid_scope whole, never a
quietly narrowed token, a scope named twice is granted once, and a request
naming none gets the client’s whole registration. The demo’s token endpoint
(apps/auth, the client_credentials grant) is all it takes:
pub(crate) fn grant_client_credentials_with_jwt( jwt_svc: &JwtService, scope: &[String], resource: &[String], client: &AuthenticatedClient,) -> Result<AccessTokenResponse, TokenError> { let scopes = client.scope_for(scope)?; let audience = client.audience_for(resource)?; // …}The token’s scope claim is the granted set, and the response states it
with AccessTokenResponse::with_scope, which RFC 6749 §5.1 requires
whenever the grant differs from the request. The client’s roles come from
its registration’s payload, never from the scopes it asks for — the two
answer different questions on the issuer’s side too. The demo’s
demo-service client is an admin of its org: asking for posts:read
alone, it reads posts, and an edit or a delete answers the challenge
below. Creating a post answers a plain 403 instead, whatever the scope:
a post’s author is a user, and no scope makes a client one, so a challenge
naming posts:write would send it after a token refused all the same.
What the refused caller receives
Section titled “What the refused caller receives”A client that cannot tell “you may never do this” from “come back with a wider token” either gives up too early or retries the same token forever. So the two refusals are distinct on every transport.
On HTTP, a scope refusal is a 403 whose RFC 6750 §3.1 challenge names
the scopes the request needs. A
protected resource server
adds the document to request them from, and carries the same challenge on
WS and MCP:
HTTP/1.1 403 ForbiddenWWW-Authenticate: Bearer error="insufficient_scope", resource_metadata="https://api.example.com/.well-known/oauth-protected-resource", scope="posts:write"The client now knows the exact scope to request and the document to
request it from. An ordinary 403 — the caller may not do this at
all, no grant or a cannot with no when — deliberately carries no
challenge, even beside a grant the token’s scopes withhold: advertising
a recovery that cannot succeed is worse than a plain refusal.
A rule cannot name a scope outside RFC 6749 §3.3’s grammar. A guard’s own
Denial::insufficient_scope can — a space, a quote — and that cannot ride the quoted
attribute: the challenge goes out without scope, and a warn names the scopes, a required scope is not a scope-token; the challenge is sent without its scope attribute.
On GraphQL there is no 403 to enrich, so the same facts ride the error
frame the transport already speaks:
{ "errors": [{ "message": "the request requires higher privileges than provided by the access token", "extensions": { "code": "INSUFFICIENT_SCOPE", "requiredScopes": ["posts:write"] } }]}The list is what one grant lacks, every scope of it needed. When several
grants would have allowed the operation, it is the one asking for fewest — the
action’s own before Action::Manage’s, then the first declared, among those asking
as many — never their union, which would send the client asking for more than it
needs.
A site gated on Manage needs every action,
so its list is the smallest that lifts all of them: one grant of each refused action,
each scope once — posts:write alone where it opens Update and is one of the two
grants opening Read — or a grant of the wildcard, which opens the four at once,
when it asks for fewer. A site no scope could lift, a denial barring one action or
an action no grant opens, names none and answers a plain 403.
The sentence is RFC 6750 §3.1’s own description of insufficient_scope, and
it is the same on every transport: one class gate,
class_gate, decides
an #[authorize] on HTTP, GraphQL, WebSocket and MCP alike.
Advertise every scope you gate on
Section titled “Advertise every scope you gate on”The scopes your rules require and the scopes your resource server
advertises must be the same set, so the set you declared is what it
advertises — the metadata document’s scopes_supported and the
challenge’s — handed to the module once:
#[module( imports = [ // … OAuthResourceModule::for_root(constants::ALL), // … ],)]pub struct AssistantModule;A deployment that sets <PREFIX>_OAUTH__RESOURCE__SCOPES_SUPPORTED
advertises that list instead, and an app declaring two sets fails the boot
naming both imports. A scope a rule requires but the metadata document
omits is a dead end — the client is told to request something discovery
never names. The framework reports it at warn
(reason="scope_not_advertised") on each such refusal;
declaring the set once and handing it to both sides is what stops it
happening.
A scope on a capability no table holds
Section titled “A scope on a capability no table holds”Not every scope names rows. The demo advertises audio:transcode, and
transcoding is a capability: there is no table to filter and no row to
judge. Declare it as a subject no table
holds and gate
it like any other rule — the scope goes on the rule, never in a guard:
use nest_rs::authz::subject;
#[subject]pub struct Transcoding;if actor.is_admin() { ab.can(Action::Manage, Transcoding) .requires_scope(constants::AUDIO_TRANSCODE);}#[post("/transcode")]#[authorize(Manage, Transcoding)]#[http_code(202)]async fn transcode(&self, Json(body): Json<TranscodeDto>) -> Result<()> { self.svc.enqueue_transcode(body.file).await.opaque()?; Ok(())}The class gate answers exactly as above: a member, whom no rule grants,
gets 403 FORBIDDEN with no challenge, since no wider token would change
it; an admin whose token was not delegated audio:transcode gets the
insufficient_scope challenge naming it; a credential that is not
scope-aware — a session, an mTLS identity — is gated on the role alone.
The same #[authorize(Manage, Transcoding)] sits on the MCP tool and on
the progress stream, so audio:transcode gates every edge it is
advertised for.
Every transport renders the denial the same way — the challenge is written once, at the transport edge, so neither a rule nor a guard formats a header itself.
Going further
Section titled “Going further”- Split deployment — the discovery document the challenge points the client at.
- Policies — the role-driven conditions a scope narrows.
- Row-level filtering — what a withheld rule means for the query.