5. Authentication: Users, Sessions & OAuth
Production-Grade Authentication Out of the Box
Supabase Auth (GoTrue) provides a complete identity management system. It handles email/password sign-up, magic links, SMS OTP, social OAuth providers (Google, GitHub, Apple, Twitter, and 20+ more), and enterprise SSO via SAML 2.0 — all configurable from the dashboard with no backend code required.
GoTrue is a lightweight Go service that manages user identities and session tokens. It stores users in the auth.users table and issues JWTs for authentication. The service handles password hashing, email verification, OAuth flows, and session management. It's designed to be secure by default — passwords are hashed with bcrypt, emails are verified before allowing access, and refresh tokens are rotated on every use. The JWT contains the user's ID, email, and any custom claims you add. This JWT is used by RLS policies to identify the user. Understanding Auth is essential for building secure applications. You'll need to configure your auth settings, set up OAuth providers, and handle user sessions properly.
Auth Flow & JWT Architecture
When a user signs in, GoTrue issues two tokens: an Access Token (JWT) and a Refresh Token. The Access Token is short-lived (~1 hour) and is sent with every API request in the Authorization header. It contains the user's id, email, role, and custom claims. The Refresh Token is long-lived and stored in an HttpOnly cookie or localStorage. It's used to obtain a new access token after it expires. The Refresh Token is single-use and rotated on every refresh for security. This means if a token is stolen, it can't be reused after the next refresh. The Supabase client SDK handles token management automatically. It stores the session in localStorage by default and refreshes the token when it expires. For server-side applications, use the @supabase/ssr package for proper cookie management. Understanding this flow helps you debug auth issues and build secure authentication.
Short-lived (~1 hour). Sent with every API request in the Authorization header. Contains the user's id, email, role, and custom claims. Verified without a database roundtrip.
Long-lived, stored in an HttpOnly cookie or localStorage. Used to get a new access token after it expires. Single-use and rotated on every refresh for security.
// Sign up with email and password const { data, error } = await supabase.auth.signUp({ email: 'user@example.com', password: 'super-secure-password', });
OAuth Providers
OAuth providers simplify authentication for users and reduce password management overhead. Google, GitHub, Apple, Twitter, and 20+ other providers are supported out of the box. To set up OAuth, configure your provider's client ID and secret in the Supabase Dashboard. The flow is: user clicks Sign in with Google, they're redirected to Google's login page, they approve the request, they're redirected back to your app with an auth code, and your app exchanges the code for a session. The Supabase client SDK handles this flow for you. You just call signInWithOAuth with the provider name and a redirectTo URL. The user's profile data is stored in auth.users.raw_user_meta_data. Remember to set up the redirectTo URL to point to your app's callback page, and call exchangeCodeForSession on that page.
// Google OAuth const { error } = await supabase.auth.signInWithOAuth({ provider: 'google', options: { redirectTo: `${window.location.origin}/auth/callback`, scopes: 'openid email profile', } });
redirectTo URL with an auth code. Your app must call supabase.auth.exchangeCodeForSession() on that page to complete the sign-in and get a session.Custom JWT Claims & Server-Side Auth
Custom JWT claims allow you to add application-specific data to the user's token. This is useful for role-based access control, feature flags, or any data you need in RLS policies. The custom_access_token_hook is a Postgres function that runs when a token is issued. It can add custom claims based on data in your profiles table. The hook receives the JWT payload as a JSONB and returns the modified payload. This is more efficient than querying the database for every request because the data is already in the token. For server-side authentication, use the createServerClient from @supabase/ssr. This provides cookie-based session management for Next.js and other SSR frameworks. Always use getUser() instead of getSession() on the server — getUser() validates the token, getSession() just reads the cookie.
-- Add custom claims to every JWT CREATE OR REPLACE FUNCTION public.custom_access_token_hook(event JSONB) RETURNS JSONB AS $$ DECLARE claims JSONB; user_role TEXT; BEGIN SELECT role INTO user_role FROM public.profiles WHERE id = (event->>'user_id')::UUID; claims := event->'claims'; claims := jsonb_set(claims, '{role}', to_jsonb(COALESCE(user_role, 'user'))); RETURN jsonb_set(event, '{claims}', claims); END; $$ LANGUAGE plpgsql STABLE;
Security Best Practices
Authentication security is critical for any application. Enable email confirmation to prevent spam signups and verify ownership. Set password strength requirements in the Auth settings. Use the PKCE flow for OAuth in server-side rendered apps to prevent token interception. Never trust client-provided user IDs — always use auth.uid() inside RLS policies. Audit with auth.users — GoTrue logs created_at, last_sign_in_at, and email_confirmed_at. Monitor these logs for suspicious activity. Use HTTPS for all requests. Store session tokens securely — HttpOnly cookies for server-side apps, localStorage for client-side only. Implement rate limiting on auth endpoints. These practices protect your users' accounts and your data.
- Enable email confirmation — prevents spam signups and verifies ownership.
- Set password strength requirements in Auth settings.
- Use PKCE flow for OAuth in server-side rendered apps to prevent token interception.
- Never trust client-provided user IDs — always use
auth.uid()inside RLS policies. - Audit with auth.users — GoTrue logs created_at, last_sign_in_at, and email_confirmed_at.
Knowledge Check
Ready to test your understanding of 5. Authentication: Users, Sessions & OAuth?