SSO Authentication Flow
This guide covers the Single Sign-On (SSO) integration using OAuth 2.0 and OpenID Connect (OIDC). The boilerplate supports robust integration with identity providers like Google and GitHub.
Architecture Overview
The SSO flow is completely built into the core domain layer (src/domain/sso), avoiding heavy framework coupling and using the clean distinction between Identities and Credentials.
Key Components
1. get-authorize.ts (The Redirect)
The entrypoint /authorize generates the necessary URL to redirect the user to the provider.
- It includes security measures such as
stategeneration to prevent CSRF attacks. - Certain providers, such as Google, might also require a
noncedepending on the requestedresponse_type.
2. get-callback.ts (The Token Exchange & Login)
Once the IDP redirects the user back to the application (/callback), this controller:
- Extracts the authorization
codefrom the query string. - Validates the
stateto ensure the session wasn't hijacked. - Calls the underlying
exchangeTokeninfrastructure to swap thecodefor anaccess_token(andid_tokenif applicable). - Generates or updates the internal
IdentityandCredential. - Finally, it provides the internal
JWTused by the application for subsequent requests.
3. oidc.ts (The Infrastructure Hook)
Located at src/infrastructure/sso/oidc.ts, this file manages all the external communication with the providers:
exchangeToken: Hits the provider's token endpoint to trade codes.verifyIdToken: A robust built-in JWT validator that fetches the provider's Public Keys (JWKS), verifies thekid(Key ID), and ensures theexp(Expiration) and signature are completely valid before trusting the token.getNormalizedUser: Maps different API contracts (e.g. Google's parsedid_tokenvs GitHub's/userendpoint) into a consistent format.
Environment Configuration
To enable SSO, setup the specific environment variables in your .env:
# Google SSO
SSO_GOOGLE_CLIENT_ID="your-client-id.apps.googleusercontent.com"
SSO_GOOGLE_CLIENT_SECRET="your-client-secret"
SSO_GOOGLE_REDIRECT_URI="http://localhost:3000/api/v1/sso/callback"
# GitHub SSO
SSO_GITHUB_CLIENT_ID="your-client-id"
SSO_GITHUB_CLIENT_SECRET="your-client-secret"
SSO_GITHUB_REDIRECT_URI="http://localhost:3000/api/v1/sso/callback"NOTE
If a provider is not configured, the boilerplate will instantly throw an error if a user attempts to use /authorize for that provider.
Security Considerations
- The OAuth flow uses JWKS validation arrays to ensure
id_tokensreceived from providers like Google belong to them and weren't tampered with. - We enforce
statecomparison across both GitHub and Google to guarantee CSRF resistance. - Access tokens inside the application are extremely short-lived, favoring refresh tokens.