Zum Inhalt springen

Generische OAuth2-Provider

GitHub

Das Capgo Social Login Plugin enthält eine integrierte OAuth2- und OpenID Connect-Engine. Damit kannst du jeden standardbasierten Identity Provider anbinden, einschließlich:

  • GitHub
  • Azure AD / Microsoft Entra ID
  • Auth0
  • Okta
  • Keycloak
  • Eigene OAuth2- oder OIDC-Server

Der oauth2 Die Konfiguration ist per Design multi-provider-fähig. Du kannst mehrere Provider gleichzeitig registrieren und dann beim Login einen auswählen mit providerId.

Bevor du einen Provider konfigurierst, sammle Folgendes:

  • Deine OAuth-Client-ID
  • Eine Redirect-URL, die zu deinem App-Scheme oder deiner Web-Callback-URL passt
  • Einen Authorization-Endpoint
  • Einen Token-Endpoint für den code-Authorization-Flow oder einen issuerUrl für die OIDC-Discovery
  • Die Scopes, die deine App braucht, zum Beispiel openid profile email

Nutzt SocialLogin.initialize() einmal beim App-Start und registriere jeden Provider, den du brauchst:

import { SocialLogin } from '@capgo/capacitor-social-login';
await SocialLogin.initialize({
oauth2: {
github: {
appId: 'your-github-client-id',
authorizationBaseUrl: 'https://github.com/login/oauth/authorize',
accessTokenEndpoint: 'https://github.com/login/oauth/access_token',
redirectUrl: 'myapp://oauth/github',
scope: 'read:user user:email',
pkceEnabled: true,
resourceUrl: 'https://api.github.com/user',
},
azure: {
appId: 'your-azure-client-id',
authorizationBaseUrl: 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize',
accessTokenEndpoint: 'https://login.microsoftonline.com/common/oauth2/v2.0/token',
redirectUrl: 'myapp://oauth/azure',
scope: 'openid profile email User.Read',
pkceEnabled: true,
resourceUrl: 'https://graph.microsoft.com/v1.0/me',
},
auth0: {
issuerUrl: 'https://your-tenant.auth0.com',
appId: 'your-auth0-client-id',
redirectUrl: 'myapp://oauth/auth0',
scope: 'openid profile email offline_access',
pkceEnabled: true,
additionalParameters: {
audience: 'https://your-api.example.com',
},
},
},
});

Wenn Ihr Anbieter ein OpenID Connect Discovery-Dokument bereitstellt, issuerUrl ist die einfachste Konfiguration:

await SocialLogin.initialize({
oauth2: {
keycloak: {
issuerUrl: 'https://sso.example.com/realms/mobile',
clientId: 'mobile-app',
redirectUrl: 'myapp://oauth/keycloak',
scope: 'openid profile email offline_access',
pkceEnabled: true,
},
},
});

Das Plugin unterstützt auch gängige OAuth- und OIDC-Aliase:

  • clientId als Alias für appId
  • authorizationEndpoint als Alias für authorizationBaseUrl
  • tokenEndpoint als Alias für accessTokenEndpoint
  • endSessionEndpoint als Alias für logoutUrl
  • scopes als Alias für scope

Auch verfügbar:

  • additionalParameters für Auth-Request-Overrides
  • additionalTokenParameters für Token-Exchange-Overrides
  • additionalResourceHeaders für Custom-Resource-Endpoint-Header
  • additionalLogoutParameters und postLogoutRedirectUrl für Logout-Flows
  • loginHint, prompt, und iosPrefersEphemeralSession

Wenn Sie von Ionic Auth Connect migrieren und dieselben Provider-Namen beibehalten möchten, verwenden Sie SocialLoginAuthConnect.

import { SocialLoginAuthConnect } from '@capgo/capacitor-social-login';
await SocialLoginAuthConnect.initialize({
authConnect: {
auth0: {
domain: 'https://your-tenant.auth0.com',
clientId: 'your-auth0-client-id',
redirectUrl: 'myapp://oauth/auth0',
audience: 'https://your-api.example.com',
},
azure: {
tenantId: 'common',
clientId: 'your-azure-client-id',
redirectUrl: 'myapp://oauth/azure',
},
okta: {
issuer: 'https://dev-12345.okta.com/oauth2/default',
clientId: 'your-okta-client-id',
redirectUrl: 'myapp://oauth/okta',
},
},
});

Unterstützte Preset-Provider-IDs:

  • auth0
  • azure
  • cognito
  • okta
  • onelogin

Wenn ein Provider benutzerdefinierte Endpunkte benötigt, überschreiben Sie diese im Preset oder umgehen Sie Presets und konfigurieren Sie den Provider direkt in oauth2.

OptionTypErforderlichBeschreibung
appId / clientIdstringJaOAuth2-Client-Identifier
issuerUrlstringNeinBasis-URL für OIDC-Discovery
authorizationBaseUrl / authorizationEndpointstringJa*URL des Autorisierungs-Endpunkts
accessTokenEndpoint / tokenEndpointstringNein*URL des Token-Endpunkts
redirectUrlstringJaCallback-URL
scope / scopesstring / string[]NeinAngeforderte Scopes
pkceEnabledbooleanNeinStandardmäßig true
responseType'code' oder 'token'NeinStandardmäßig 'code'
resourceUrlstringNeinUser-Info- oder Resource-Endpoint
logoutUrl / endSessionEndpointstringNeinLogout- oder End-Session-URL
postLogoutRedirectUrlstringNeinRedirect-URL nach Logout
additionalParametersRecord<string, string>NeinZusätzliche Auth-Request-Parameter
additionalTokenParametersRecord<string, string>NeinZusätzliche Token-Request-Parameter
additionalResourceHeadersRecord<string, string>NeinZusätzliche Header für resourceUrl
additionalLogoutParametersRecord<string, string>NeinZusätzliche Logout-Parameter
loginHintstringNeinKürzel für additionalParameters.login_hint
promptstringNeinKürzel für additionalParameters.prompt
iosPrefersEphemeralSessionbooleanNeinEphemere Browser-Sitzung auf iOS bevorzugen
logsEnabledbooleanNeinAusführliche Debug-Protokollierung aktivieren

authorizationBaseUrl und accessTokenEndpoint sind nur optional, wenn issuerUrl für die Discovery ausreicht. Explizite Endpunkte haben immer Vorrang vor den entdeckten Werten.

const result = await SocialLogin.login({
provider: 'oauth2',
options: {
providerId: 'github',
scope: 'read:user user:email',
loginHint: 'user@example.com',
},
});

Nutzt flow: 'redirect' wenn du einen Full-Page-Redirect statt eines Popups möchtest:

await SocialLogin.login({
provider: 'oauth2',
options: {
providerId: 'auth0',
flow: 'redirect',
},
});

Auf der Seite, die den Callback empfängt, das Login-Ergebnis parsen:

const result = await SocialLogin.handleRedirectCallback();
if (result?.provider === 'oauth2') {
console.log(result.result.providerId);
}
const status = await SocialLogin.isLoggedIn({
provider: 'oauth2',
providerId: 'github',
});
await SocialLogin.logout({
provider: 'oauth2',
providerId: 'github',
});
await SocialLogin.refresh({
provider: 'oauth2',
options: {
providerId: 'github',
},
});
const refreshed = await SocialLogin.refreshToken({
provider: 'oauth2',
providerId: 'github',
refreshToken: 'existing-refresh-token',
});

refresh() verwendet den vom Plugin gespeicherten Refresh Token. refreshToken() ermöglicht es Ihnen, ein Refresh-Token selbst zu übergeben, und gibt die aktuelle OAuth2-Antwort zurück.

const code = await SocialLogin.getAuthorizationCode({
provider: 'oauth2',
providerId: 'github',
});
console.log(code.accessToken);

Nutze GitHub, wenn du einen einfachen OAuth-App-Flow und grundlegende Profildaten brauchst:

await SocialLogin.initialize({
oauth2: {
github: {
appId: 'your-github-client-id',
authorizationBaseUrl: 'https://github.com/login/oauth/authorize',
accessTokenEndpoint: 'https://github.com/login/oauth/access_token',
redirectUrl: 'myapp://oauth/github',
scope: 'read:user user:email',
pkceEnabled: true,
resourceUrl: 'https://api.github.com/user',
},
},
});
const githubResult = await SocialLogin.login({
provider: 'oauth2',
options: {
providerId: 'github',
},
});
console.log(githubResult.result.accessToken?.token);
console.log(githubResult.result.resourceData);

Azure AD / Microsoft Entra ID-Beispiel

Abschnitt: „Azure AD / Microsoft Entra ID-Beispiel“

Verwenden Sie Azure, wenn Sie auf Microsoft Graph-Daten wie das Benutzerprofil zugreifen müssen:

await SocialLogin.initialize({
oauth2: {
azure: {
appId: 'your-azure-client-id',
authorizationBaseUrl: 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize',
accessTokenEndpoint: 'https://login.microsoftonline.com/common/oauth2/v2.0/token',
redirectUrl: 'myapp://oauth/azure',
scope: 'openid profile email User.Read',
pkceEnabled: true,
resourceUrl: 'https://graph.microsoft.com/v1.0/me',
},
},
});
const azureResult = await SocialLogin.login({
provider: 'oauth2',
options: {
providerId: 'azure',
},
});
console.log(azureResult.result.idToken);
console.log(azureResult.result.resourceData);

Auth0 eignet sich gut, wenn Sie OIDC plus eine eigene API-Audience brauchen:

await SocialLogin.initialize({
oauth2: {
auth0: {
appId: 'your-auth0-client-id',
authorizationBaseUrl: 'https://your-tenant.auth0.com/authorize',
accessTokenEndpoint: 'https://your-tenant.auth0.com/oauth/token',
redirectUrl: 'myapp://oauth/auth0',
scope: 'openid profile email offline_access',
pkceEnabled: true,
additionalParameters: {
audience: 'https://your-api.example.com',
},
},
},
});
const auth0Result = await SocialLogin.login({
provider: 'oauth2',
options: {
providerId: 'auth0',
flow: 'redirect',
},
});

Wenn Sie im Web den Redirect-Flow nutzen, lesen Sie das Ergebnis auf der Callback-Seite aus:

const auth0Result = await SocialLogin.handleRedirectCallback();
if (auth0Result?.provider === 'oauth2') {
console.log(auth0Result.result.idToken);
}
await SocialLogin.initialize({
oauth2: {
okta: {
appId: 'your-okta-client-id',
authorizationBaseUrl: 'https://your-domain.okta.com/oauth2/default/v1/authorize',
accessTokenEndpoint: 'https://your-domain.okta.com/oauth2/default/v1/token',
redirectUrl: 'myapp://oauth/okta',
scope: 'openid profile email offline_access',
pkceEnabled: true,
resourceUrl: 'https://your-domain.okta.com/oauth2/default/v1/userinfo',
},
},
});
const oktaResult = await SocialLogin.login({
provider: 'oauth2',
options: {
providerId: 'okta',
},
});
console.log(oktaResult.result.resourceData);

Nutzen Sie Discovery, wenn Ihr Provider sie veröffentlicht /.well-known/openid-configuration:

await SocialLogin.initialize({
oauth2: {
keycloak: {
issuerUrl: 'https://sso.example.com/realms/mobile',
clientId: 'mobile-app',
redirectUrl: 'myapp://oauth/keycloak',
scope: 'openid profile email offline_access',
pkceEnabled: true,
},
},
});
const keycloakResult = await SocialLogin.login({
provider: 'oauth2',
options: {
providerId: 'keycloak',
},
});
console.log(keycloakResult.result.idToken);

Erfolgreiche OAuth2-Logins geben zurück:

FeldBeschreibung
providerIdDer konfigurierte Provider-Key, der für das Login verwendet wurde
accessTokenAccess-Token-Payload oder null
idTokenOIDC-ID-Token, falls der Provider eines zurückgegeben hat
refreshTokenRefresh-Token, falls die angeforderten Scopes es erlaubten
resourceDataRoh-JSON abgerufen von resourceUrl
scopeVergebene Scopes
tokenTypeMeist bearer
expiresInToken-Lebensdauer in Sekunden
  1. OAuth-App erstellen Öffne GitHub Entwickler-Einstellungen und eine neue OAuth-App erstellen.

  2. Callback-URL festlegen Verwenden Sie die Redirect-URL Ihrer App, z. B. myapp://oauth/github.

  3. Plugin konfigurieren

    await SocialLogin.initialize({
    oauth2: {
    github: {
    appId: 'your-github-client-id',
    authorizationBaseUrl: 'https://github.com/login/oauth/authorize',
    accessTokenEndpoint: 'https://github.com/login/oauth/access_token',
    redirectUrl: 'myapp://oauth/github',
    scope: 'read:user user:email',
    pkceEnabled: true,
    resourceUrl: 'https://api.github.com/user',
    },
    },
    });
  1. App registrieren Öffnen Sie das Azure Portal und App registrations, und erstellen Sie eine native oder mobile App-Registrierung.

  2. Redirect-URI hinzufügen Fügen Sie eine mobile oder Desktop-Redirect-URI hinzu, die Ihrer App-Callback-URL entspricht.

  3. Plugin konfigurieren

    await SocialLogin.initialize({
    oauth2: {
    azure: {
    appId: 'your-azure-client-id',
    authorizationBaseUrl: 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize',
    accessTokenEndpoint: 'https://login.microsoftonline.com/common/oauth2/v2.0/token',
    redirectUrl: 'myapp://oauth/azure',
    scope: 'openid profile email User.Read',
    pkceEnabled: true,
    resourceUrl: 'https://graph.microsoft.com/v1.0/me',
    },
    },
    });
  1. Eine native App erstellen Öffne die Auth0-Dashboard und erstelle eine Native App.

  2. Erlaubte Callback-URLs festlegen Füge die exakte Redirect-URL hinzu, die deine Capacitor App verwendet.

  3. Plugin konfigurieren

    await SocialLogin.initialize({
    oauth2: {
    auth0: {
    appId: 'your-auth0-client-id',
    authorizationBaseUrl: 'https://your-tenant.auth0.com/authorize',
    accessTokenEndpoint: 'https://your-tenant.auth0.com/oauth/token',
    redirectUrl: 'myapp://oauth/auth0',
    scope: 'openid profile email offline_access',
    pkceEnabled: true,
    additionalParameters: {
    audience: 'https://your-api.example.com',
    },
    logoutUrl: 'https://your-tenant.auth0.com/v2/logout',
    },
    },
    });
  1. Eine OIDC Native App erstellen Erstelle in der Okta Admin Console eine OIDC Native Application.

  2. Redirect URI hinzufügen Registriere die exakte Callback-URL, die deine App verwendet.

  3. Plugin konfigurieren

    await SocialLogin.initialize({
    oauth2: {
    okta: {
    appId: 'your-okta-client-id',
    authorizationBaseUrl: 'https://your-domain.okta.com/oauth2/default/v1/authorize',
    accessTokenEndpoint: 'https://your-domain.okta.com/oauth2/default/v1/token',
    redirectUrl: 'myapp://oauth/okta',
    scope: 'openid profile email offline_access',
    pkceEnabled: true,
    resourceUrl: 'https://your-domain.okta.com/oauth2/default/v1/userinfo',
    },
    },
    });

Falls dein Provider OpenID Connect Discovery unterstützt, nutze vorzugsweise issuerUrl:

await SocialLogin.initialize({
oauth2: {
keycloak: {
issuerUrl: 'https://sso.example.com/realms/mobile',
clientId: 'mobile-app',
redirectUrl: 'myapp://oauth/keycloak',
scope: 'openid profile email offline_access',
pkceEnabled: true,
},
},
});

Wenn Discovery nicht verfügbar ist, konfiguriere die Authorization- und Token-Endpoints manuell.

  • Das Plugin verwendet ASWebAuthenticationSession.
  • Setzen Sie iosPrefersEphemeralSession: true wenn du eine private Browser-Sitzung ohne geteilte Cookies möchtest.
  • OAuth-Redirects werden über deinen App-Scheme und Host zurückgegeben.
  • Stelle sicher, dass die Callback-URL des Providers exakt mit deinem Android-Deep-Link-Setup übereinstimmt.
  • Das Plugin übernimmt die OAuth-Activity bereits. Füge nur dann eigene Intent-Filter hinzu, wenn deine App ein anderes Redirect-Pattern benötigt.
  • Der Popup-Flow ist der Standard und eignet sich gut für Single-Page-Apps.
  • Der Redirect-Flow ist besser, wenn der Provider Popups blockiert oder deine Auth-Regeln eine Top-Level-Navigation erfordern.
  • Einige Provider blockieren den direkten Token-Austausch im Browser via CORS. Nutze in diesen Fällen einen Backend-Exchange oder ein Provider-Setup, das Public Clients erlaubt.
  1. Nutze PKCE Behalten pkceEnabled: true für Public Clients.

  2. Authorization code Flow bevorzugen responseType: 'code' ist sicherer als der Implicit Flow.

  3. Tokens im Backend validieren Issuer, Audience, Ablaufdatum und Signatur serverseitig decodieren und verifizieren.

  4. Refresh Tokens sicher speichern Für Native Apps dieses Plugin mit kombinieren @capgo/capacitor-persistent-account.

  5. HTTPS überall verwenden Auth- und Logout-Endpunkte in der Produktion sollten immer HTTPS verwenden.

Jede OAuth2-Methode benötigt den konfigurierten Provider-Key:

await SocialLogin.login({
provider: 'oauth2',
options: { providerId: 'github' },
});

Rufe SocialLogin.initialize() vor dem Login und stellen Sie sicher, dass providerId dem Objekt-Key unter oauth2.

Redirect-URL stimmt nicht überein

Abschnitt mit dem Titel „Redirect URL mismatch“
  • Vergleichen Sie die konfigurierte Redirect-URL in Ihrer App und im Provider-Dashboard Zeichen für Zeichen.
  • Achten Sie auf schließende Schrägstriche, Schema-Abweichungen und unterschiedliche Hosts.
  • Stelle sicher, dass die URL-Schemes der mobilen App vor dem Test auf dem Gerät registriert sind.

Die meisten Anbieter geben Refresh-Tokens nur zurück, wenn du Scopes wie offline_access anforderst oder die Zustimmung explizit erzwingst. Prüfe die anbieterspezifische Richtlinie.

Aktivieren logsEnabled: true in der Anbieter-Konfiguration, um generierte URLs und Details zum Token-Austausch zu prüfen.

Wenn du es nutzt Generische OAuth2-Provider Um Authentifizierungs- und Account-Flows zu planen, verbinde es mit @capgo/capacitor-social-login verwenden für die native Funktion bei der Verwendung von @capgo/capacitor-social-login, @capgo/capacitor-social-login für die Implementierungsdetails in @capgo/capacitor-social-login, @capgo/capacitor-passkey für die Implementierungsdetails in @capgo/capacitor-passkey, @capgo/capacitor-native-biometric für die Implementierungsdetails in @capgo/capacitor-native-biometric, und Zwei-Faktor-Authentifizierung für die Implementierungsdetails zur Zwei-Faktor-Authentifizierung.