Authentication overview

SuperTokens offers a self-hosted, open-source approach to user authentication and session management. Unlike cloud-based identity providers, SuperTokens is deployed within a developer's infrastructure, providing direct control over the authentication stack and user data SuperTokens overview guide. This architecture is designed for applications requiring complete ownership of the identity solution and customization of authentication flows.

The system comprises a core service that handles the fundamental authentication logic and various SDKs for integrating with different backend and frontend frameworks. Developers integrate these SDKs into their application to manage user sign-up, login, session creation, and other identity-related operations. The core service manages token issuance, verification, and revocation, supporting standards like JSON Web Tokens (JWTs) for session management IETF JWT specification.

SuperTokens emphasizes providing building blocks for authentication rather than a fully opinionated, locked-down service. This allows developers to implement specific authentication policies, integrate with existing systems, and maintain compliance requirements such as GDPR by keeping user data within their control SuperTokens compliance features.

Supported authentication methods

SuperTokens supports a range of authentication methods, allowing developers to choose based on application requirements and user experience goals. These methods are configurable through the SuperTokens core and its SDKs.

Core Authentication Methods

  • Email and Password: Traditional username/password authentication with built-in password hashing and security features.
  • Passwordless Login: Allows users to log in using a magic link sent to their email or phone number, or a one-time password (OTP).
  • Social Login: Integration with third-party identity providers such as Google, GitHub, Facebook, and others, enabling users to log in with existing social accounts.
  • Multi-factor Authentication (MFA): Adds an extra layer of security by requiring users to verify their identity using a second factor, such as a time-based one-time password (TOTP) from an authenticator app SuperTokens MFA documentation.

Session Management

Beyond initial authentication, SuperTokens provides comprehensive session management capabilities. This includes:

  • Short-lived Access Tokens: Issued for API authorization, typically expiring quickly.
  • Long-lived Refresh Tokens: Used to obtain new access tokens without requiring the user to re-authenticate frequently.
  • Anti-CSRF Protection: Mechanisms to prevent Cross-Site Request Forgery attacks SuperTokens Anti-CSRF protection.
  • Session Revocation: Programmatic invalidation of user sessions.

The following table summarizes the primary authentication methods available through SuperTokens:

Method When to Use Security Level
Email and Password Standard web applications, internal tools, B2B services Medium (reliant on strong password policies and user discipline)
Passwordless (Magic Link/OTP) Improved user experience, reduced password fatigue, mobile-first applications Medium to High (dependent on email/phone security; less susceptible to credential stuffing)
Social Login (OAuth/OpenID Connect) Consumer-facing applications, rapid onboarding, leveraging existing trusted identities High (security delegated to the social identity provider like Google Developers) Google OAuth 2.0 documentation
Multi-factor Authentication (MFA) High-security applications, financial services, PII handling, compliance requirements Very High (adds a secondary verification layer, significantly reduces unauthorized access risk)

Getting your credentials

SuperTokens operates differently from cloud-based identity providers where API keys or client secrets are issued by the vendor. Since SuperTokens is self-hosted, developers configure and manage their own credentials and secrets directly within their application's environment.

For Self-Hosted SuperTokens Core

The core SuperTokens service does not require external credentials to operate once deployed. Its security is managed through network access controls, server hardening, and proper configuration of its internal services. Communication between the SuperTokens core and your application's backend is typically secured via internal network configurations or TLS/SSL SuperTokens deployment guide.

For Social Logins (OAuth/OpenID Connect)

When integrating social login providers like Google, GitHub, or Facebook, you will need to obtain client IDs and client secrets directly from those respective identity providers. These credentials enable your SuperTokens instance to act as an OAuth client and communicate securely with the social login provider to authenticate users OAuth 2.0 specification.

The process generally involves:

  1. Registering your application with the chosen social identity provider (e.g., in the Google Cloud Console for Google Sign-In).
  2. Configuring authorized redirect URIs to point back to your SuperTokens instance or application backend.
  3. Obtaining the generated Client ID and Client Secret.
  4. Configuring these credentials within your SuperTokens backend SDK (e.g., in your Node.js or Python backend) to enable the specific social login method SuperTokens social login configuration.

These credentials should be treated as sensitive information and stored securely, typically as environment variables or in a secrets management system, rather than hardcoded in source control.

Authenticated request example

After a user successfully authenticates with SuperTokens, the system issues session tokens (access and refresh tokens). Subsequent authenticated requests from the client (e.g., a web browser or mobile app) to your application's backend API typically include the access token in the Authorization header.

Here's an example using a common HTTP request pattern. This example assumes a Node.js backend using the SuperTokens SDK and a frontend making an API call.

Frontend (React/JavaScript) example:

import SuperTokens from 'supertokens-web-js';
import { getAccessToken } from 'supertokens-web-js/recipe/session';

async function callAuthenticatedApi() {
  try {
    const accessToken = await getAccessToken();
    if (!accessToken) {
      // User is not logged in or session expired
      console.log('No active session.');
      return;
    }

    const response = await fetch('/api/data/protected',
      {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${accessToken}`,
        },
      }
    );

    if (response.ok) {
      const data = await response.json();
      console.log('Protected data:', data);
    } else if (response.status === 401) {
      console.log('Session expired or unauthorized. Refreshing session...');
      // SuperTokens web SDK automatically tries to refresh the session
      // If refresh fails, it will redirect to login page (if configured)
    } else {
      console.log('API error:', response.status);
    }
  } catch (error) {
    console.error('Error making authenticated request:', error);
  }
}

// Call this function when you need to access protected data
callAuthenticatedApi();

Backend (Node.js with SuperTokens Express SDK) example:

On the backend, your API endpoint would use the SuperTokens SDK to verify the incoming access token and retrieve session information.

const express = require('express');
const supertokens = require('supertokens-node');
const { verifySession } = require('supertokens-node/recipe/session/framework/express');
const app = express();

// SuperTokens initialization and configuration (not shown for brevity)
// supertokens.init({...});

app.get('/api/data/protected', verifySession(), async (req, res) => {
  try {
    // If verifySession passes, the session object is available on req.session
    const userId = req.session.getUserId();
    console.log(`User ${userId} accessed protected data.`);

    // Fetch and return protected data
    res.json({ message: `Hello, user ${userId}! This is protected data.` });
  } catch (error) {
    // This catch block would typically handle errors not caught by verifySession
    // For example, if database access fails after authentication
    console.error('Error fetching protected data:', error);
    res.status(500).send('Internal Server Error');
  }
});

app.listen(3001, () => {
  console.log('Backend listening on port 3001');
});

In this backend example, verifySession() is a middleware provided by SuperTokens that automatically extracts the access token from the request header, validates it, and attaches session information to the request object. If the token is invalid or expired, it handles the response (e.g., sending a 401 Unauthorized status) and potentially triggers a session refresh flow SuperTokens API reference.

Security best practices

Implementing SuperTokens for authentication requires adherence to general security best practices for identity management and API security. Given its self-hosted nature, developers have direct responsibility for many security aspects.

  • Secure Deployment Environment: Deploy the SuperTokens core service in a secured environment, preferably within a private network or with strict firewall rules limiting access only to necessary application components. Keep the underlying operating system and dependencies updated to patch known vulnerabilities.
  • HTTPS/TLS Everywhere: Always use HTTPS for all communication between your frontend, backend, and the SuperTokens core. This encrypts data in transit, protecting credentials and session tokens from eavesdropping MDN Web Docs on TLS.
  • Strong Password Policies: If using email/password authentication, enforce strong password requirements (length, complexity, uniqueness) and implement rate limiting on login attempts to mitigate brute-force attacks.
  • Input Validation and Sanitization: Validate and sanitize all user inputs, especially for authentication-related fields, to prevent injection attacks (e.g., SQL injection, XSS) that could compromise user accounts or the system.
  • Secure Credential Storage: Store all sensitive credentials (e.g., social login client secrets, API keys) securely using environment variables, dedicated secrets management services, or encrypted configuration files. Avoid hardcoding credentials in source code.
  • Session Security: Leverage SuperTokens's built-in session management features like short-lived access tokens, long-lived refresh tokens, and anti-CSRF protection. Ensure proper handling of refresh tokens, storing them securely (e.g., HTTP-only cookies) to prevent XSS attacks.
  • Multi-factor Authentication (MFA): Enable and encourage MFA for all users, especially for applications handling sensitive data. This adds a critical layer of security beyond just passwords.
  • Regular Security Audits and Penetration Testing: Periodically audit your SuperTokens configuration, application code, and infrastructure for vulnerabilities. Conduct penetration testing to identify and remediate potential security weaknesses.
  • Logging and Monitoring: Implement comprehensive logging for authentication events (successful logins, failed attempts, account lockouts) and monitor these logs for suspicious activity. Set up alerts for anomalies.
  • Keep SDKs and Core Updated: Regularly update SuperTokens core and client/backend SDKs to benefit from security patches and new features.