$npx -y skills add mjunaidca/mjs-agent-skills --skill configuring-better-authImplement OAuth 2.1 / OIDC authentication using Better Auth with MCP assistance. Use when setting up a centralized auth server (SSO provider), implementing SSO clients in Next.js apps, configuring PKCE flows, or managing tokens with JWKS verification. Uses Better Auth MCP for gui
| 1 | # Better Auth OAuth/OIDC |
| 2 | |
| 3 | Implement centralized authentication with Better Auth - either as an auth server or SSO client. |
| 4 | |
| 5 | ## MCP Server Setup |
| 6 | |
| 7 | Better Auth provides an MCP server powered by Chonkie for guided configuration: |
| 8 | |
| 9 | ```bash |
| 10 | claude mcp add --transport http better-auth https://mcp.chonkie.ai/better-auth/better-auth-builder/mcp |
| 11 | ``` |
| 12 | |
| 13 | Or in `settings.json`: |
| 14 | |
| 15 | ```json |
| 16 | { |
| 17 | "mcpServers": { |
| 18 | "better-auth": { |
| 19 | "type": "http", |
| 20 | "url": "https://mcp.chonkie.ai/better-auth/better-auth-builder/mcp" |
| 21 | } |
| 22 | } |
| 23 | } |
| 24 | ``` |
| 25 | |
| 26 | ### When to Use the MCP |
| 27 | |
| 28 | | Task | Use MCP? | |
| 29 | |------|----------| |
| 30 | | Initial Better Auth setup | Yes - guided configuration | |
| 31 | | Adding OIDC provider plugin | Yes - generates correct config | |
| 32 | | Troubleshooting auth issues | Yes - can analyze setup | |
| 33 | | Understanding auth flow | Yes - explains concepts | |
| 34 | | Writing custom middleware | No - use patterns below | |
| 35 | |
| 36 | --- |
| 37 | |
| 38 | ## Architecture Overview |
| 39 | |
| 40 | ``` |
| 41 | ┌─────────────────┐ |
| 42 | │ Better Auth SSO │ ← Central auth server (auth-server-setup.md) |
| 43 | │ (Auth Server) │ |
| 44 | └────────┬────────┘ |
| 45 | │ |
| 46 | ┌────┴────┐ |
| 47 | ▼ ▼ |
| 48 | ┌───────┐ ┌───────┐ |
| 49 | │ App 1 │ │ App 2 │ ← SSO clients (sso-client-integration.md) |
| 50 | └───────┘ └───────┘ |
| 51 | ``` |
| 52 | |
| 53 | --- |
| 54 | |
| 55 | ## Quick Start: Auth Server Setup |
| 56 | |
| 57 | ```bash |
| 58 | npm install better-auth @better-auth/oidc-provider drizzle-orm |
| 59 | ``` |
| 60 | |
| 61 | ### Core Configuration |
| 62 | |
| 63 | ```typescript |
| 64 | // src/lib/auth.ts |
| 65 | import { betterAuth } from "better-auth"; |
| 66 | import { drizzleAdapter } from "better-auth/adapters/drizzle"; |
| 67 | import { oidcProvider } from "better-auth/plugins/oidc-provider"; |
| 68 | |
| 69 | export const auth = betterAuth({ |
| 70 | database: drizzleAdapter(db, { provider: "pg", schema }), |
| 71 | emailAndPassword: { enabled: true }, |
| 72 | session: { |
| 73 | expiresIn: 60 * 60 * 24 * 7, // 7 days |
| 74 | updateAge: 60 * 60 * 24, // 1 day |
| 75 | }, |
| 76 | plugins: [ |
| 77 | oidcProvider({ |
| 78 | loginPage: "/sign-in", |
| 79 | consentPage: "/consent", |
| 80 | // PKCE for public clients (recommended) |
| 81 | requirePKCE: true, |
| 82 | }), |
| 83 | ], |
| 84 | }); |
| 85 | ``` |
| 86 | |
| 87 | ### Register OAuth Clients |
| 88 | |
| 89 | ```typescript |
| 90 | // Register SSO client |
| 91 | await auth.api.createOAuthClient({ |
| 92 | name: "My App", |
| 93 | redirectUris: ["http://localhost:3000/api/auth/callback"], |
| 94 | type: "public", // Use 'public' for PKCE |
| 95 | }); |
| 96 | ``` |
| 97 | |
| 98 | See [references/auth-server-setup.md](references/auth-server-setup.md) for complete setup with JWKS, email verification, and admin dashboard. |
| 99 | |
| 100 | --- |
| 101 | |
| 102 | ## Quick Start: SSO Client Integration |
| 103 | |
| 104 | ```bash |
| 105 | npm install jose |
| 106 | ``` |
| 107 | |
| 108 | ### Environment Variables |
| 109 | |
| 110 | ```env |
| 111 | NEXT_PUBLIC_SSO_URL=http://localhost:3001 |
| 112 | NEXT_PUBLIC_SSO_CLIENT_ID=your-client-id |
| 113 | ``` |
| 114 | |
| 115 | ### PKCE Auth Flow |
| 116 | |
| 117 | ```typescript |
| 118 | // lib/auth-client.ts |
| 119 | import { generateCodeVerifier, generateCodeChallenge } from "./pkce"; |
| 120 | |
| 121 | export async function startLogin() { |
| 122 | const verifier = generateCodeVerifier(); |
| 123 | const challenge = await generateCodeChallenge(verifier); |
| 124 | |
| 125 | // Store verifier in cookie |
| 126 | document.cookie = `pkce_verifier=${verifier}; path=/; SameSite=Lax`; |
| 127 | |
| 128 | const params = new URLSearchParams({ |
| 129 | client_id: process.env.NEXT_PUBLIC_SSO_CLIENT_ID!, |
| 130 | redirect_uri: `${window.location.origin}/api/auth/callback`, |
| 131 | response_type: "code", |
| 132 | scope: "openid profile email", |
| 133 | code_challenge: challenge, |
| 134 | code_challenge_method: "S256", |
| 135 | }); |
| 136 | |
| 137 | window.location.href = `${SSO_URL}/oauth2/authorize?${params}`; |
| 138 | } |
| 139 | ``` |
| 140 | |
| 141 | ### Token Exchange (API Route) |
| 142 | |
| 143 | ```typescript |
| 144 | // app/api/auth/callback/route.ts |
| 145 | export async function GET(request: Request) { |
| 146 | const { searchParams } = new URL(request.url); |
| 147 | const code = searchParams.get("code"); |
| 148 | const verifier = cookies().get("pkce_verifier")?.value; |
| 149 | |
| 150 | const response = await fetch(`${SSO_URL}/oauth2/token`, { |
| 151 | method: "POST", |
| 152 | headers: { "Content-Type": "application/x-www-form-urlencoded" }, |
| 153 | body: new URLSearchParams({ |
| 154 | grant_type: "authorization_code", |
| 155 | client_id: process.env.NEXT_PUBLIC_SSO_CLIENT_ID!, |
| 156 | code: code!, |
| 157 | redirect_uri: `${process.env.NEXT_PUBLIC_APP_URL}/api/auth/callback`, |
| 158 | code_verifier: verifier!, |
| 159 | }), |
| 160 | }); |
| 161 | |
| 162 | const tokens = await response.json(); |
| 163 | |
| 164 | // Set httpOnly cookies |
| 165 | const res = NextResponse.redirect("/dashboard"); |
| 166 | res.cookies.set("access_token", tokens.access_token, { httpOnly: true }); |
| 167 | res.cookies.set("refresh_token", tokens.refresh_token, { httpOnly: true }); |
| 168 | return res; |
| 169 | } |
| 170 | ``` |
| 171 | |
| 172 | See [references/sso-client-integration.md](references/sso-client-integration.md) for JWKS verification, token refresh, and global logout. |
| 173 | |
| 174 | --- |
| 175 | |
| 176 | ## PKCE Utilities |
| 177 | |
| 178 | ```typescript |
| 179 | // lib/pkce.ts |
| 180 | export function generateCodeVerifier(): string { |
| 181 | const array = new Uint8Array(32); |
| 182 | crypto.getRandomValues(array); |
| 183 | re |