Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

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…

mjunaidcaот mjunaidca★ 27 звёзд на GitHub4 установки в других каталогах

Об этом скилле

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

  1. 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?
  2. Database

    • Which database? (Postgres recommended with Neon for serverless)
    • Need user profiles beyond core auth fields?
  3. 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
Полный SKILL.md на GitHub

Установить 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), без исполняемых скриптов.

Похожие скиллы

Сравнить better-auth-setup с