How to implement social login with Litestar
Based on the Litestar Fullstack Inertia showcase project.
Prerequisites
For social authorization to work, you first need to register your application with the identity provider (e.g., GitHub).
Implementation
Frontend
You need a login or registration page with a button/link that sends the browser to a backend route which starts the OAuth2 flow. For social login, it doesn’t matter whether you call it “login” or “registration”, as the first login typically creates the user.
Implementation details:
– In the showcase project it’s implemented in partials:
– Login form
– Registration form
– Both partials use the same button, which handles clicks with router.post(route("github.register")).
– route() is an Inertia.js helper function which simply resolves handler names to paths.
– A plain link and HTTP GET would also work here, since no data is sent at this stage.
Login/Register handler (backend)
Create a route that redirects to the provider’s authorization URL and includes a callback pointing to your completion handler.
For production you should generate OAuth2 state and PKCE code verifier, and store them in the session.
Implementation details:
– See the authorization controller
– You can use httpx_oauth to get auth-related URLs for popular OAuth2 providers.
Authorization callback handler (backend)
Your callback (named “github.complete” in the showcase) should:
- Validate the store OAuth2 state (required for security; missing in the showcase)
- Exchange the authorization code for an access token
- Create a user object in the local database and store the user Id in the session
- Redirect to a post-login page (e.g., dashboard)
Optionally:
– Fetch user details (e.g., email) from the provider
– Provide user data to the frontend
Implementation details:
– The showcase doesn't use OAuth2 state or PKCE
– GitHubOAuth2.get_access_token is used to exchange the auth code for a token (wrapped as a Litestar dependency, to facilitate re-use)
– GitHubOAuth2.get_id_email is used to retrieve users email
– Inertia’s share() is used to pass user details to the frontend
© 2025 Matte Silver
