Zum Inhalt springen

Bessere Auth-Integration

Better Auth funktioniert gut mit @capgo/capacitor-social-login wenn Sie eine native Anmeldung auf dem Gerät wünschen, aber dennoch möchten, dass Better Auth die Sitzung auf Ihrem Backend erstellt und verwaltet.

Diese Seite konzentriert sich auf die zwei Integrationsschemata, die am besten passen:

  • Native Token-Übergabe für Google, Apple und Facebook
  • Better Auth Generic OAuth für Anbieter wie Auth0, Okta, Keycloak und benutzerdefinierte OIDC-Server

Verwenden Sie SocialLogin.login() Zuerst und dann senden Sie den zurückgegebenen Token an Better Auth mit authClient.signIn.social() wenn Sie verwenden:

  • Google
  • Apple
  • Facebook

Lassen Sie Better Auth den vollständigen OAuth-Redirect-Flow besitzen, wenn Sie verwenden:

  • Auth0
  • Okta
  • Keycloak
  • GitHub
  • OneLogin
  • Jeder beliebige OAuth2- oder OIDC-Anbieter

Damit bleibt die Sitzungsübertragung auf der Better Auth-Seite und es wird die Doppelung der Redirect-Logik zwischen zwei Systemen vermieden.

Auf die Zwischenablage kopieren

import { betterAuth } from 'better-auth';
export const auth = betterAuth({
baseURL: process.env.BETTER_AUTH_URL,
socialProviders: {
google: {
clientId: process.env.GOOGLE_CLIENT_ID as string,
clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
},
apple: {
clientId: process.env.APPLE_CLIENT_ID as string,
clientSecret: process.env.APPLE_CLIENT_SECRET as string,
appBundleIdentifier: process.env.APPLE_APP_BUNDLE_IDENTIFIER as string,
},
facebook: {
clientId: process.env.FACEBOOK_CLIENT_ID as string,
clientSecret: process.env.FACEBOOK_CLIENT_SECRET as string,
},
},
trustedOrigins: ['https://appleid.apple.com'],
});
import { createAuthClient } from 'better-auth/client';
export const authClient = createAuthClient({
baseURL: 'https://auth.example.com',
});

Wenn Sie React verwenden, verwenden Sie das Better Auth-React-Kundenpaket, das Ihre App bereits verwendet. Der Token-Übergabepattern bleibt gleich.

Dies ist der sauberste Integrationsweg für nativ mobil Google-Anmeldung:

import { SocialLogin } from '@capgo/capacitor-social-login';
import { authClient } from '@/lib/auth-client';
const googleResult = await SocialLogin.login({
provider: 'google',
options: {
scopes: ['profile', 'email'],
},
});
if (googleResult.result.responseType !== 'online' || !googleResult.result.idToken) {
throw new Error('Google online mode with idToken is required for Better Auth.');
}
await authClient.signIn.social({
provider: 'google',
idToken: {
token: googleResult.result.idToken,
accessToken: googleResult.result.accessToken?.token,
},
callbackURL: '/dashboard',
});

Für Apple wird der gleiche Nonce sowohl beim nativen Anmeldeantrag als auch bei Better Auth übergeben:

import { SocialLogin } from '@capgo/capacitor-social-login';
import { authClient } from '@/lib/auth-client';
const nonce = crypto.randomUUID();
const appleResult = await SocialLogin.login({
provider: 'apple',
options: {
scopes: ['email', 'name'],
nonce,
},
});
if (!appleResult.result.idToken) {
throw new Error('Apple idToken is required for Better Auth.');
}
await authClient.signIn.social({
provider: 'apple',
idToken: {
token: appleResult.result.idToken,
nonce,
accessToken: appleResult.result.accessToken?.token,
},
callbackURL: '/dashboard',
});

Better Auth dokumentiert zwei Facebook-Handover-Modi:

  • iOS Limited Login: übergeben Sie den idToken
  • Zugriffstoken-Fluss: übergeben Sie den Zugriffstoken als sowohl token und accessToken

Dies funktioniert mit der Antwortform von @capgo/capacitor-social-login:

import { SocialLogin } from '@capgo/capacitor-social-login';
import { authClient } from '@/lib/auth-client';
const facebookResult = await SocialLogin.login({
provider: 'facebook',
options: {
permissions: ['email', 'public_profile'],
},
});
const betterAuthToken = facebookResult.result.idToken
? {
token: facebookResult.result.idToken,
}
: facebookResult.result.accessToken?.token
? {
token: facebookResult.result.accessToken.token,
accessToken: facebookResult.result.accessToken.token,
}
: null;
if (!betterAuthToken) {
throw new Error('Facebook idToken or access token is required for Better Auth.');
}
await authClient.signIn.social({
provider: 'facebook',
idToken: betterAuthToken,
callbackURL: '/dashboard',
});

Für Auth0, Okta, Keycloak, GitHub, Microsoft Entra ID und ähnliche Anbieter ist der Generic OAuth-Plugin von Better Auth in der Regel besser geeignet als das Weitergeben von Token von SocialLogin.login({ provider: 'oauth2' }).

import { betterAuth } from 'better-auth';
import { genericOAuth } from 'better-auth/plugins';
export const auth = betterAuth({
plugins: [
genericOAuth({
config: [
{
providerId: 'keycloak',
discoveryUrl: 'https://sso.example.com/realms/mobile/.well-known/openid-configuration',
clientId: process.env.KEYCLOAK_CLIENT_ID as string,
clientSecret: process.env.KEYCLOAK_CLIENT_SECRET as string,
},
],
}),
],
});
import { createAuthClient } from 'better-auth/client';
import { genericOAuthClient } from 'better-auth/client/plugins';
export const authClient = createAuthClient({
baseURL: 'https://auth.example.com',
plugins: [genericOAuthClient()],
});
await authClient.signIn.oauth2({
providerId: 'keycloak',
callbackURL: '/dashboard',
});

Better Auth liefert vor konfigurierte Hilfsfunktionen für mehrere Anbieter. Diese sind die nächste Annäherung an die zusätzlichen Beispielanbieter, die Sie in den Dokumentationen der Social-Login-Plugin sehen.

import { betterAuth } from 'better-auth';
import { auth0, genericOAuth } from 'better-auth/plugins';
export const auth = betterAuth({
plugins: [
genericOAuth({
config: [
auth0({
providerId: 'auth0',
domain: 'dev-example.eu.auth0.com',
clientId: process.env.AUTH0_CLIENT_ID as string,
clientSecret: process.env.AUTH0_CLIENT_SECRET as string,
scopes: ['openid', 'profile', 'email', 'offline_access'],
}),
],
}),
],
});
await authClient.signIn.oauth2({
providerId: 'auth0',
callbackURL: '/dashboard',
});
import { betterAuth } from 'better-auth';
import { genericOAuth, microsoftEntraId } from 'better-auth/plugins';
export const auth = betterAuth({
plugins: [
genericOAuth({
config: [
microsoftEntraId({
providerId: 'entra',
tenantId: 'common',
clientId: process.env.AZURE_CLIENT_ID as string,
clientSecret: process.env.AZURE_CLIENT_SECRET as string,
scopes: ['openid', 'profile', 'email', 'User.Read'],
}),
],
}),
],
});
await authClient.signIn.oauth2({
providerId: 'entra',
callbackURL: '/dashboard',
});
import { betterAuth } from 'better-auth';
import { genericOAuth, okta } from 'better-auth/plugins';
export const auth = betterAuth({
plugins: [
genericOAuth({
config: [
okta({
providerId: 'okta',
issuer: 'https://dev-12345.okta.com/oauth2/default',
clientId: process.env.OKTA_CLIENT_ID as string,
clientSecret: process.env.OKTA_CLIENT_SECRET as string,
scopes: ['openid', 'profile', 'email', 'offline_access'],
}),
],
}),
],
});
await authClient.signIn.oauth2({
providerId: 'okta',
callbackURL: '/dashboard',
});
import { betterAuth } from 'better-auth';
import { genericOAuth, keycloak } from 'better-auth/plugins';
export const auth = betterAuth({
plugins: [
genericOAuth({
config: [
keycloak({
providerId: 'keycloak',
issuer: 'https://sso.example.com/realms/mobile',
clientId: process.env.KEYCLOAK_CLIENT_ID as string,
clientSecret: process.env.KEYCLOAK_CLIENT_SECRET as string,
scopes: ['openid', 'profile', 'email', 'offline_access'],
}),
],
}),
],
});
await authClient.signIn.oauth2({
providerId: 'keycloak',
callbackURL: '/dashboard',
});

GitHub hat auf der Generic OAuth-Seite keinen Better Auth-Helfer, daher wird manuelle Konfiguration verwendet:

import { betterAuth } from 'better-auth';
import { genericOAuth } from 'better-auth/plugins';
export const auth = betterAuth({
plugins: [
genericOAuth({
config: [
{
providerId: 'github',
clientId: process.env.GITHUB_CLIENT_ID as string,
clientSecret: process.env.GITHUB_CLIENT_SECRET as string,
authorizationUrl: 'https://github.com/login/oauth/authorize',
tokenUrl: 'https://github.com/login/oauth/access_token',
userInfoUrl: 'https://api.github.com/user',
scopes: ['read:user', 'user:email'],
pkce: true,
},
],
}),
],
});
await authClient.signIn.oauth2({
providerId: 'github',
callbackURL: '/dashboard',
});
  1. Verwendung von Google-Online-Modus Better Auth benötigt idToken, so google.mode: 'offline' passt nicht für diesen Handover-Flow.

  2. Wiederhole den Apple-Nonce Erstelle ihn einmal, sende ihn an Apple native Login, dann sende denselben Wert an Better Auth.

  3. Behandle Facebook unterschiedlich, je nach Plattform Limited Login auf iOS gibt dir einen ID-Token. Andere Flows geben nur ein Zugriffstoken.

  4. Mische keine Generic OAuth-Flows, es sei denn, du hast einen Grund dafür Wenn Better Auth die OAuth-Anbieterkonfiguration besitzt, soll Better Auth auch den Redirect-Flow besitzen.