better-auth-setup
БесплатноБез исполняемых скриптовНе проверенGuide implementation of OAuth 2.1 / OIDC authentication using Better Auth with the OIDC Provider plugin. Use this skill when setting up centralized…
Об этом скилле
Better Auth OAuth/OIDC Setup Skill
Purpose
Guide implementation of OAuth 2.1 / OIDC authentication using Better Auth with the OIDC Provider plugin.
When to Use
- Setting up centralized authentication for multiple apps
- Implementing SSO (Single Sign-On) across a platform
- Creating an OAuth authorization server
- Integrating Better Auth as an identity provider
Key Questions to Ask
Architecture
- How many apps will use this auth server?
- Is this for first-party apps only or third-party OAuth clients too?
- Do you need dynamic client registration?
Database
- Which database? (Postgres recommended with Neon for serverless)
- Need user profiles beyond core auth fields?
Features
- Role-based access control needed?
- Admin dashboard for user management?
- Consent screen for third-party apps?
Implementation Checklist
1. Auth Server Setup (Public Client with PKCE)
// src/lib/auth.ts
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { oidcProvider } from "better-auth/plugins/oidc-provider";
import { admin } from "better-auth/plugins/admin";
export const auth = betterAuth({
database: drizzleAdapter(db, { provider: "pg", schema }),
emailAndPassword: { enabled: true },
session: {
expiresIn: 60 * 60 * 24 * 7, // 7 days
updateAge: 60 * 60 * 24, // Refresh daily
},
trustedOrigins: process.env.ALLOWED_ORIGINS?.split(","),
plugins: [
oidcProvider({
loginPage: "/auth/sign-in",
consentPage: "/auth/consent",
trustedClients: [{
clientId: "your-app",
// No clientSecret for public clients - use PKCE instead
type: "public", // Public client for SPAs
redirectUrls: ["http://localhost:3000/auth/callback"], // Note: lowercase 'urls'
skipConsent: true, // First-party apps
}],
// Add custom claims to userinfo
async getAdditionalUserInfoClaim(user) {
return { role: user.role };
},
}),
admin({
defaultRole: "user",
adminRoles: ["admin"],
}),
],
});
2. OAuth Client with PKCE (Recommended for SPAs)
// Client app: src/lib/auth-client.ts
// PKCE helpers
function generateCodeVerifier(): string {
const array = new Uint8Array(32);
crypto.getRandomValues(array);
return base64UrlEncode(array);
}
async function generateCodeChallenge(verifier: string): Promise<string> {
const hash = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier));
return base64UrlEncode(new Uint8Array(hash));
}
// Authorization URL with PKCE
export async function getOAuthAuthorizationUrl(state: string) {
const codeVerifier = generateCodeVerifier();
const codeChallenge = await generateCodeChallenge(codeVerifier);
// Store verifier for token exchange
sessionStorage.setItem('pkce_code_verifier', codeVerifier);
const params = new URLSearchParams({
client_id: 'your-app',
redirect_uri: 'http://localhost:3000/auth/callback',
response_type: 'code',
scope: 'openid profile email',
state,
code_challenge: codeChallenge,
code_challenge_method: 'S256',
});
return `${AUTH_SERVER_URL}/api/auth/oauth2/authorize?${params}`;
}
// Callback: exchange code for tokens with PKCE (no client_secret!)
const codeVerifier = sessionStorage.getItem('pkce_code_verifier');
const tokenResponse = await fetch(`${AUTH_SERVER_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: 'http://localhost:3000/auth/callback',
client_id: 'your-app',
code_verifier: codeVerifier, // PKCE: verifier instead of secret
}),
});
sessionStorage.removeItem('pkce_code_verifier');
3. Session Management (Client)
// AuthContext.tsx pattern
const checkSession = async () => {
const accessToken = localStorage.getItem('access_token');
if (accessToken) {
const response = await fetch(`${AUTH_URL}/api/auth/oauth2/userinfo`, {
headers: { Authorization: `Bearer ${accessToken}` },
});
if (response.ok) {
setSession({ user: await response.json() });
} else {
localStorage.removeItem('access_token');
}
}
};
const signOut = () => {
localStorage.removeItem('access_token');
localStorage.removeItem('refresh_token');
setSession(null);
window.location.href = '/';
};
4. Admin-Only Client Registration (Custom Endpoint)
Better Auth's built-in /api/auth/oauth2/register endpoint allows dynamic client registration but doesn't enforce admin-only access. For production environments where you want to control who can register OAuth clients, create a custom admin-only endpoint:
// src/app/api/admin/clients/register/route.ts
import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/li
Установить better-auth-setup в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл better-auth-setup?
Guide implementation of OAuth 2.1 / OIDC authentication using Better Auth with the OIDC Provider plugin. Use this skill when setting up centralized authentication for multiple apps, implementing SSO across a platform, creating an OAuth authorization server, or integrating Better Auth as an identity provider. Covers PKCE for public clients, JWKS configuration, token management, email verification, and common pitfalls like preserving PKCE parameters during sign-in redirects.
Как установить скилл better-auth-setup?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл better-auth-setup запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
doc-coauthoring
Guide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision…
от Anthropicacademy-guide
Stop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials…
от Anthropicinternal-comms
A set of resources to help me write all kinds of internal communications, using the formats that my company likes to use. Claude should use this skill…
от Anthropicskill-development
This skill should be used when the user wants to "create a skill", "add a skill to plugin", "write a new skill", "improve skill description", "organize skill…
от Anthropic