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.
- 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
npm install adapt-auth-sdk// 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!,
},
});// 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!
}
);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');
}π 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
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"- SAML 2.0 signature validation
- Encrypted cookie sessions
- CSRF protection
- TypeScript-first with strict typing
- Framework-agnostic design
- Simple, intuitive API
- Comprehensive error handling
- Detailed logging with automatic PII redaction
- Serverless/stateless architecture
- Cookie-only sessions (no server storage)
- Comprehensive test coverage
const session = await auth.getSession();
if (session) {
console.log('User:', session.user.name);
console.log('Authenticated:', await auth.isAuthenticated());
}// 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'
}
});// 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';
}// 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));
}
}const auth = createAdaptNext({
// ... config
callbacks: {
mapProfile: async (profile) => ({
id: profile.encodedSUID,
email: `${profile.userName}@stanford.edu`,
name: `${profile.firstName} ${profile.lastName}`,
department: profile.department,
}),
},
});// 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' };GNU Version 3 License - see LICENSE for details.
Contributions are welcome! Please read our contributing guidelines and submit pull requests to our GitHub repository.
Security issues should be reported privately. Please do not open public GitHub issues for security vulnerabilities.
- π Documentation
- π Issues