better-auth-sso
БесплатноБез исполняемых скриптовНе проверенIntegrate with Better Auth SSO for OAuth2/OIDC authentication. Use this skill when implementing SSO login flows, PKCE authentication, token management, JWKS…
от mjunaidca★ 27 звёзд на GitHubОб этом скилле
Better Auth SSO Integration
Integrate Next.js applications with Better Auth SSO using OAuth 2.1 / OIDC with PKCE flow.
When to Use
- Implementing SSO login in Next.js apps
- Setting up PKCE-based OAuth flow (public clients)
- Managing tokens in httpOnly cookies
- Verifying JWTs using JWKS
- Implementing global logout across apps
Architecture Overview
┌─────────────────┐
│ Better Auth SSO │ ← Central auth server
│ (Auth Server) │
└────────┬────────┘
│
┌────┴────┐
▼ ▼
┌───────┐ ┌───────┐
│ App 1 │ │ App 2 │ ← Tenant apps (SSO clients)
└───────┘ └───────┘
Quick Start
# Dependencies
npm install jose
# Environment
NEXT_PUBLIC_SSO_URL=http://localhost:3001
NEXT_PUBLIC_SSO_CLIENT_ID=your-client-id
Core Patterns
1. PKCE Authentication Client
// lib/auth-client.ts
const SSO_URL = process.env.NEXT_PUBLIC_SSO_URL!;
const CLIENT_ID = process.env.NEXT_PUBLIC_SSO_CLIENT_ID!;
// Base64URL encoding helper
function base64UrlEncode(buffer: Uint8Array): string {
const base64 = btoa(String.fromCharCode(...buffer));
return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
// Generate cryptographically secure code verifier
export function generateCodeVerifier(): string {
const array = new Uint8Array(32);
crypto.getRandomValues(array);
return base64UrlEncode(array);
}
// Generate SHA-256 code challenge
export async function generateCodeChallenge(verifier: string): Promise<string> {
const encoder = new TextEncoder();
const data = encoder.encode(verifier);
const hash = await crypto.subtle.digest('SHA-256', data);
return base64UrlEncode(new Uint8Array(hash));
}
// Build OAuth authorization URL with PKCE
export async function getOAuthAuthorizationUrl(
callbackUrl?: string
): Promise<string> {
const codeVerifier = generateCodeVerifier();
const codeChallenge = await generateCodeChallenge(codeVerifier);
const state = generateCodeVerifier(); // Random state
// Store for token exchange
sessionStorage.setItem('pkce_code_verifier', codeVerifier);
sessionStorage.setItem('oauth_state', state);
if (callbackUrl) {
sessionStorage.setItem('oauth_callback_url', callbackUrl);
}
const params = new URLSearchParams({
client_id: CLIENT_ID,
redirect_uri: `${window.location.origin}/api/auth/callback`,
response_type: 'code',
scope: 'openid profile email',
state,
code_challenge: codeChallenge,
code_challenge_method: 'S256',
});
return `${SSO_URL}/api/auth/oauth2/authorize?${params}`;
}
// Get stored PKCE verifier
export function getStoredCodeVerifier(): string | null {
return sessionStorage.getItem('pkce_code_verifier');
}
// Clear PKCE storage
export function clearPKCEStorage(): void {
sessionStorage.removeItem('pkce_code_verifier');
sessionStorage.removeItem('oauth_state');
sessionStorage.removeItem('oauth_callback_url');
}
2. OAuth Callback Route
// app/api/auth/callback/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
const SSO_URL = process.env.NEXT_PUBLIC_SSO_URL!;
const CLIENT_ID = process.env.NEXT_PUBLIC_SSO_CLIENT_ID!;
export async function GET(request: NextRequest) {
const searchParams = request.nextUrl.searchParams;
const code = searchParams.get('code');
const state = searchParams.get('state');
const error = searchParams.get('error');
if (error) {
return NextResponse.redirect(new URL(`/login?error=${error}`, request.url));
}
if (!code) {
return NextResponse.redirect(new URL('/login?error=no_code', request.url));
}
// Get code verifier from cookie (set by client before redirect)
const cookieStore = await cookies();
const codeVerifier = cookieStore.get('pkce_code_verifier')?.value;
if (!codeVerifier) {
return NextResponse.redirect(
new URL('/login?error=no_verifier', request.url)
);
}
try {
// Exchange code for tokens (PKCE - no client secret!)
const tokenResponse = await fetch(`${SSO_URL}/api/auth/oauth2/token`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'authorization_code',
code,
redirect_uri: `${new URL(request.url).origin}/api/auth/callback`,
client_id: CLIENT_ID,
code_verifier: codeVerifier,
}),
});
if (!tokenResponse.ok) {
const error = await tokenResponse.text();
console.error('Token exchange failed:', error);
return NextResponse.redirect(
new URL('/login?error=token_exchange', request.url)
);
}
const tokens = await tokenResponse.json();
// Create response with redirect
const callbackUrl = cookieStore.get('oauth_callback_url')?.value || '/dashboard';
const response = NextResponse.redirect(new URL(callbackUrl, request.url));
// Set httpOnly cookies for tokens
const cookieOptions = {
Установить better-auth-sso в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл better-auth-sso?
Integrate with Better Auth SSO for OAuth2/OIDC authentication. Use this skill when implementing SSO login flows, PKCE authentication, token management, JWKS verification, or global logout in Next.js applications connecting to a Better Auth server.
Как установить скилл better-auth-sso?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл better-auth-sso запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic