Social login
Open provider contract — each provider is one module import, active once its credentials are set, and a third party publishes its own through the same seam.
Social login is an open provider contract. The framework ships the
SocialProvider trait, an inventory-based registry, and first-party
GitHub and Google providers. SocialModule holds the registry; each
provider is one more import, and turns on when its credentials are
configured. A third party publishes a new provider as its own crate
through the same seam — no fork, no framework change.
Install
Section titled “Install”cargo add nest-rs --features socialThe social feature implies oauth-client, which implies authn: the authorization-code machinery
SocialModule drives (OAuthClient, TokenSet) arrives with it.
use nest_rs::core::module;use nest_rs::social::{GithubSocialModule, GoogleSocialModule};
#[module(imports = [GithubSocialModule, GoogleSocialModule, SignInHttpModule])]pub struct AuthModule;SocialModule owns the registry, which each provider’s module imports, and
each provider’s module opens that provider: a provider whose module the app does not import stays closed,
whatever its credentials say. So every provider an app can log in with is
a line in its composition root, and an opening is never a side effect of
a dependency.
SignInHttpModule is yours — the two routes below are app code, for the
reason The request flow explains, and what they run
around the provider is the framework’s.
Wire it in
Section titled “Wire it in”Each provider reads its credentials from the dual-path config
(<PREFIX>_SOCIAL__<PROVIDER>__* env or a provided struct). Only the
client id, secret, and redirect URL are deployment config — the
auth/token/userinfo endpoints are provider constants, and scopes
default to each provider’s canonical login set.
NESTRS_SOCIAL__GITHUB__CLIENT_ID=…NESTRS_SOCIAL__GITHUB__CLIENT_SECRET=…NESTRS_SOCIAL__GITHUB__REDIRECT_URL=https://auth.example/social/github/callback
NESTRS_SOCIAL__GOOGLE__CLIENT_ID=…NESTRS_SOCIAL__GOOGLE__CLIENT_SECRET=…NESTRS_SOCIAL__GOOGLE__REDIRECT_URL=https://auth.example/social/google/callback<PREFIX>_SOCIAL__GITHUB__SCOPES and <PREFIX>_SOCIAL__GOOGLE__SCOPES take a
comma-separated list and default to each provider’s canonical login set, so
neither is deployment config until you need more than sign-in. Each entry is one
RFC 6749 §3.3 scope-token: SCOPES="openid email" is one entry holding a space,
and fails the boot naming the variable — write openid,email.
What a provider reads beyond the client’s own parameters goes in
<PREFIX>_SOCIAL__<PROVIDER>__AUTHORIZATION_PARAMETERS, a JSON object under the names
the provider documents. Google issues a refresh token only to a request saying
access_type=offline, and on a consent already given only with prompt=consent:
NESTRS_SOCIAL__GOOGLE__AUTHORIZATION_PARAMETERS='{"access_type":"offline","prompt":"consent"}'NESTRS_SOCIAL__GITHUB__AUTHORIZATION_PARAMETERS='{"prompt":"select_account"}'The client sends response_type, client_id, redirect_uri, scope, state,
code_challenge and code_challenge_method itself, and reads the answer where
response_mode, request and request_uri would move it, so naming one of those —
or nonce, in any case — fails the boot, as does a parameter with no value or named
twice. So does a credential of the client’s, client_secret, client_assertion or
client_assertion_type, and its PKCE code_verifier: those go to the token endpoint
alone, never into the authorization URL every browser is redirected to. The refresh
token reaches your SocialSignIn with the provider’s access token.
Three outcomes per imported provider, and no fourth:
Config for <PREFIX>_SOCIAL__<PROVIDER>__* |
Outcome |
|---|---|
| Complete | active |
| Absent entirely | inert — one boot warn naming the provider and its <PREFIX>_SOCIAL__<PROVIDER>__* namespace; the registry does not know the key, so /social/{provider}/authorize answers 404 and its callback 401 |
| Partial, or invalid | boot fails, naming the provider |
Real credentials are a deployment’s explicit intent, so a provider never activates by accident; and a half-configured login never starts serving silently.
Note what you do not write: neither SocialModule nor a provider’s
module takes configuration. Each provider carries its own #[config], and its
registry entry names it — so opening a provider is what loads its credentials.
Adding a provider is three lines: its crate in Cargo.toml, its module in
your imports, its credentials in the environment. The import is not
optional. A dependency line alone does not even link a crate no code names —
the provider’s registry entry would never exist, and nothing could tell
you it is missing — and importing the module is what names it.
A provider’s credentials are deployment data — the client id, the secret and the redirect URL all differ between your laptop and production — so they have no pinned-in-code path, and that is deliberate rather than missing. A test that must not read the ambient environment seeds the config on the builder, the same hard pin every other config uses.
The request flow
Section titled “The request flow”nest-rs-social ships no routes. A social provider is not a DI provider —
it is reached only through SocialRegistry, never injected by type. The
two HTTP legs are app code for what only the app decides: the path
prefix, the throttle, the resources a sign-in may ask for, and what “this
profile is a user here” means. Everything RFC 6749 fixes is the framework’s.
Two legs, both dispatched by a {provider} path segment:
GET /social/{provider}/authorize— begins the redirect. A plain handler returns whatSocialRegistry::authorize(provider, jwt, resource)answers, aSocialRedirect: a302to the provider with the PKCE/CSRF transaction in a signed, short-lived cookie, underCache-Control: no-store, so no cache keeps the response that set it. The transaction carries the RFC 8707resourcethe sign-in asked for (?resource=), signed, so the callback mints for it. A provider no imported module registers answers the404problem a route that does not exist does. Which resources a sign-in may name is yours to check before you ask.GET /social/{provider}/callback— the redirect URI, guarded byAuthnGuard<SocialStrategy<S>>. The strategy reads RFC 6749 §4.1.2’s response against the transaction cookie, exchanges the code, fetches the profile, and hands it, with the provider’s tokens, to yourSocialSignIn, which says who that profile is here; the handler reads the principal asAmbient<…>and issues this app’s token. A forged, expired or foreign transaction, or anotherstate, is a401before anything else in the response is read. A provider’s own refusal (§4.1.2.1’serror:access_deniedwhen the user cancelled), once matched, is a401—server_errorandtemporarily_unavailablea503— and the edge’sguard denied the requestonnest_rs::authnnames the registered code in itserrorchain; the response never does. Do not mark this route#[public], or the guard’s denial is absorbed and the failure surfaces as a missing principal instead.
Your part of the callback is one trait:
#[async_trait]impl SocialSignIn for SignInService { type Principal = Caller;
async fn sign_in( &self, profile: SocialProfile, _tokens: TokenSet, resource: Option<&str>, ) -> Result<Caller, AuthError> { let user = self .users_svc .resolve_social_identity(&social_identity(profile), self.config.default_org_id) .await?; Ok(Caller { user_id: user.id, org_id: user.org_id, roles: vec![role_from_db(user.role)], resource: resource.map(str::to_owned), }) }}pub fn authorize( &self, provider: &str, resource: Option<&str>,) -> Result<SocialRedirect, TokenError> { self.sign_in_audience(resource)?; Ok(self .providers .authorize(provider, &self.jwt_svc, resource)?)}// …pub type SocialGuard = AuthnGuard<SocialStrategy<SignInService>>;#[controller(path = "/")]pub struct SignInController { #[inject] svc: Arc<SignInService>,}
#[routes]impl SignInController { // … #[get("/social/{provider}/authorize")] #[public] #[use_guards(ThrottlerGuard)] // … #[meta(…)], #[api(…)] async fn social_authorize( &self, Piped(provider): Piped<Lowercase, Path<String>>, query: Query<AuthorizeDto>, ) -> Result<SocialRedirect> { Ok(self.svc.authorize(&provider, query.0.resource.as_deref())?) }
#[get("/social/{provider}/callback")] #[use_guards(ThrottlerGuard, SocialGuard)] // … #[meta(…)], #[api(…)] async fn social_callback(&self, caller: Ambient<Caller>) -> Result<AccessTokenResponse> { Ok(self.svc.issue( caller.resource.as_deref(), caller.user_id, caller.org_id, caller.roles.clone(), )?) } // …}The module listing the controller lists the strategy and its guard
beside it, SocialStrategy<SignInService> and SocialGuard.
Both legs run through the shared authorization-code flow — the same PKCE and stateless-CSRF machinery documented in OAuth2, and the same bounds on every call to the provider: a provider that stops answering fails the callback within seconds, naming the endpoint, rather than holding it. A provider only supplies the piece that is genuinely provider-specific: how to read the profile.
GitHub’s profile does not say whether its email is verified, so the GitHub
provider reads the verified-emails endpoint too (the user:email scope).
When that call fails — an outage, a revoked scope — the login goes on with
the profile email, unverified, and says so once at warn on
nest_rs::social, with provider = "github" and the call’s error: a
returning user on that fallback cannot reach their account until the
lookup answers again.
Write your own provider
Section titled “Write your own provider”A provider is real code behind a public trait, discovered at link time and opened by its module: Writing a social provider walks its three files.
Configuration
Section titled “Configuration”Per provider, under <PREFIX>_SOCIAL__<PROVIDER>__: CLIENT_ID,
CLIENT_SECRET, REDIRECT_URL, and optional SCOPES (a comma list;
defaults to the provider’s login set). The secret is secret-shaped —
keep it out of committed config.
REDIRECT_URL is an https URL, or http on a loopback address
(http://localhost:3000/…, RFC 8252 §7.3) in a declared development or
test profile (<PREFIX>_ENV) alone; any other is refused at boot, naming
<PREFIX>_SOCIAL__<PROVIDER>__REDIRECT_URL and the profile.
The provider’s own endpoints are https
constants, verified against the system’s authorities, and a custom
provider’s fetch refuses a URL that is not https — the call carries
the user’s access token.
Going further
Section titled “Going further”- OAuth2 — the shared authorization-code client every provider composes.
- Split deployment — where the token this flow issues is verified.
- Instances — instance markers, the tool for a closed set of static roles (distinct from the open provider set here).