Skip to content

SU-SWS/adapt-auth-sdk

Repository files navigation

ADAPT Auth SDK

Version 2

A framework-agnostic TypeScript authentication library for Stanford Pass SAML integration. Designed for serverless, stateless environments with security-first defaults and cookie-only sessions.

Features

  • Framework Agnostic: Works with Next.js, Express.js, and any Web API framework
  • TypeScript First: Complete TypeScript implementation with strict typing
  • Security Focused: Encrypted sessions, CSRF protection
  • Serverless Ready: Cookie-only sessions, no server-side storage required
  • Edge Compatible: Session validation in edge functions for ultra-fast performance
  • Developer Friendly: Simple API inspired by Auth.js patterns

Quick Start

Installation

npm install adapt-auth-sdk

Basic Usage (Next.js)

// lib/auth.ts
import { createAdaptNext } from 'adapt-auth-sdk/next';

export const auth = createAdaptNext({
  saml: {
    issuer: process.env.ADAPT_AUTH_SAML_ENTITY!,
    idpCert: process.env.ADAPT_AUTH_SAML_CERT!,
    callbackOrigin: process.env.ADAPT_AUTH_SAML_CALLBACK_ORIGIN!,
  },
  session: {
    name: 'adapt-auth',
    secret: process.env.ADAPT_AUTH_SESSION_SECRET!,
  },
});

Basic Usage (Framework-Agnostic)

// For other frameworks or custom implementations
import { SAMLProvider, SessionManager, createWebCookieStore } from 'adapt-auth-sdk';

const samlProvider = new SAMLProvider({
  issuer: process.env.ADAPT_AUTH_SAML_ENTITY!,
  idpCert: process.env.ADAPT_AUTH_SAML_CERT!,
  callbackOrigin: process.env.ADAPT_AUTH_SAML_CALLBACK_ORIGIN!,
});

const sessionManager = new SessionManager(
  createWebCookieStore(req, res),
  { 
    name: 'adapt-auth',
    secret: process.env.ADAPT_AUTH_SESSION_SECRET!
  }
);

Optional Configuration

The SDK uses sensible defaults, but you can customize any behavior:

export const auth = createAdaptNext({
  saml: {
    // Required
    issuer: process.env.ADAPT_AUTH_SAML_ENTITY!,
    idpCert: process.env.ADAPT_AUTH_SAML_CERT!,
    callbackOrigin: process.env.ADAPT_AUTH_SAML_CALLBACK_ORIGIN!,

    // Optional - customize as needed
    serviceProviderLoginUrl: 'https://custom.stanford.edu/api/sso/login',
    callbackPath: '/custom/callback',
    privateKey: process.env.ADAPT_AUTH_SAML_PRIVATE_KEY,
    decryptionPvk: process.env.ADAPT_AUTH_SAML_DECRYPTION_KEY,
    wantAssertionsSigned: true,
    wantAuthnResponseSigned: true,
    acceptedClockSkewMs: 60000, // 1 minute
    allowCreate: false,
    additionalParams: { custom: 'value' },
    additionalAuthorizeParams: { prompt: 'login' },
  },
  session: {
    // Required
    name: 'adapt-auth',  // Creates 'adapt-auth' (main) and 'adapt-auth-session' (JS) cookies
    secret: process.env.ADAPT_AUTH_SESSION_SECRET!,

    // Optional - customize as needed
    cookie: {
      httpOnly: true,
      secure: true,
      sameSite: 'strict',
      path: '/',
      maxAge: 86400, // 1 day
    },
    cookieSizeThreshold: 3500,
  },

  // Optional global settings
  logger: customLogger,
  verbose: process.env.NODE_ENV === 'development',
});
// app/api/auth/login/route.ts
export async function GET() {
  return auth.login({ finalDestination: '/dashboard' });
}

// app/api/auth/callback/route.ts
export async function POST(request: Request) {
  const { user, session, finalDestination } = await auth.authenticate(request);
  const redirectUrl = finalDestination || '/dashboard';
  return Response.redirect(redirectUrl);
}

// app/api/auth/logout/route.ts
export async function POST() {
  await auth.logout();
  return Response.redirect('/login');
}

Documentation

πŸ“š Getting Started - Installation and basic setup for Next.js and Express.js

βš™οΈ Configuration - Complete configuration reference and environment variables

πŸ”’ Security - Security features, best practices, and threat protection

⚑ Edge Functions - Ultra-fast session validation in edge environments

πŸš€ Advanced Usage - Custom implementations, performance optimization, and advanced patterns

πŸ“– API Reference - Complete API documentation with examples

πŸ”„ Migration Guide - Migrating from v1.x and other authentication libraries

Environment Variables

Set these required environment variables:

ADAPT_AUTH_SAML_ENTITY="your-saml-entity-id"
ADAPT_AUTH_SAML_CERT="-----BEGIN CERTIFICATE-----..."
ADAPT_AUTH_SAML_CALLBACK_ORIGIN="https://your-app.com"
ADAPT_AUTH_SESSION_SECRET="your-32-character-minimum-secret"

Key Features

Security First

  • SAML 2.0 signature validation
  • Encrypted cookie sessions
  • CSRF protection

Developer Experience

  • TypeScript-first with strict typing
  • Framework-agnostic design
  • Simple, intuitive API
  • Comprehensive error handling
  • Detailed logging with automatic PII redaction

Production Ready

  • Serverless/stateless architecture
  • Cookie-only sessions (no server storage)
  • Comprehensive test coverage

Quick Examples

Getting User Session

const session = await auth.getSession();
if (session) {
  console.log('User:', session.user.name);
  console.log('Authenticated:', await auth.isAuthenticated());
}

Updating Session Data

// Add custom metadata to session
await auth.updateSession({
  meta: {
    theme: 'dark',
    language: 'en',
    lastVisited: '/dashboard',
    preferences: { notifications: true }
  }
});

// Update user information in session
const currentSession = await auth.getSession();
await auth.updateSession({
  user: {
    ...currentSession?.user,
    displayName: 'John Doe',
    avatar: '/images/avatar.jpg'
  }
});

Client-Side Authentication Check

// Check authentication status in browser JavaScript
import { isAuthenticated } from 'adapt-auth-sdk/session';

if (isAuthenticated('adapt-auth')) {
  console.log('User is authenticated');
} else {
  window.location.href = '/api/auth/login';
}

Protecting Routes

// Next.js middleware
export async function middleware(request: NextRequest) {
  const session = await auth.getSession(request);
  if (!session && request.nextUrl.pathname.startsWith('/protected')) {
    return Response.redirect(new URL('/api/auth/login', request.url));
  }
}

Custom Profile Mapping

const auth = createAdaptNext({
  // ... config
  callbacks: {
    mapProfile: async (profile) => ({
      id: profile.encodedSUID,
      email: `${profile.userName}@stanford.edu`,
      name: `${profile.firstName} ${profile.lastName}`,
      department: profile.department,
    }),
  },
});

Edge Function Session Validation

// Ultra-fast session checking in edge functions
import { isAuthenticatedEdge } from 'adapt-auth-sdk/edge-session';

export async function middleware(request: NextRequest) {
  const isAuthenticated = await isAuthenticatedEdge(request);
  if (!isAuthenticated && request.nextUrl.pathname.startsWith('/protected')) {
    return Response.redirect(new URL('/api/auth/login', request.url));
  }
}

export const config = { runtime: 'edge' };

License

GNU Version 3 License - see LICENSE for details.

Contributing

Contributions are welcome! Please read our contributing guidelines and submit pull requests to our GitHub repository.

Security

Security issues should be reported privately. Please do not open public GitHub issues for security vulnerabilities.

Support

About

Connect style middleware for SAML authentication with ADAPT SSO SP and IDCS IDP

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 8