Add Google, Apple, Facebook and other social sign-ins to your Capacitor app with one plugin and one API across iOS, Android and the web.
Capgo: push fixes to your Capacitor users in minutes, build signed iOS and Android apps without a Mac, and roll back in one click.
14-day unlimited free trial. No credit card required
🤖 Building with an AI coding agent? Install Capgo skills so Claude Code, Codex, Cursor, Copilot, or Gemini CLI know how to install and use
@capgo/capacitor-social-loginin your Capacitor app:npx skills add Cap-go/capgo-skills. Then ask your agent: "Add @capgo/capacitor-social-login to my Capacitor app and wire it up." Agent setup guides · Hosted MCP
We build, improve and fix our plugins with heavy use of AI, so issues usually get fixed in under a day and pull requests get feedback the same day. A human still reviews and merges 50+ pull requests daily.
- Most plugin issues get a fix pull request the same day, often within a couple of hours, and are usually resolved in one to two days.
- Every pull request goes through our AI review system, usually within minutes.
- Our AI pre-checks tests, code review, conventions and security, then a human validates and merges.
- A human, Martin, reviews and merges 50+ pull requests every day.
- In the last 90 days, 95% of plugin issues were resolved.
Learn more about how we build with AI
- Many providers: Google, Apple, Facebook, Twitter (X), LinkedIn, TikTok, Telegram and generic OAuth2.
- One API:
initialize(),login(),logout(),isLoggedIn()andgetAuthorizationCode(). - Tokens:
refresh(),refreshToken(),decodeIdToken()and expiry helpers. - Native sign-in: Sign in with Apple, Google Sign-In and the Facebook SDK on iOS, Credential Manager on Android.
- Web OAuth:
handleRedirectCallback()andopenSecureWindow()for redirect and popup flows. - Platforms: iOS, Android and Web. Check the docs for each provider's setup on each platform.
This plugin is a fork of @codetrix-studio/capacitor-google-auth. We created this fork because the original plugin is "virtually" archived with no way to reach the maintainer in any medium, and only one person (@reslear) has write rights but doesn't handle native code.
If you're currently using @codetrix-studio/capacitor-google-auth, we recommend migrating to this plugin. You can follow our migration guide here.
All social logins in one plugin
This plugin implements social auth for:
- Google (with credential manager)
- Apple (with OAuth on android)
- Facebook (with latest SDK)
- Twitter/X (OAuth 2.0)
- Telegram (Login Widget)
- LinkedIn (OAuth 2.0 / OpenID Connect)
- TikTok (Login Kit / OAuth2)
- Generic OAuth2 (supports multiple providers: GitHub, Azure AD, Auth0, Okta, and any OAuth2-compliant server)
This plugin is the all-in-one solution for social authentication on Web, iOS, and Android. It is our official alternative to the Appflow Social Login plugin.
This plugin is designed to be compatible with Ionic Auth Connect provider names using the built-in OAuth2 engine.
Use the Auth Connect preset wrapper (SocialLoginAuthConnect) to log in with auth0, azure, cognito, okta, and onelogin.
- Compatibility guide: https://github.com/Cap-go/capacitor-social-login/blob/main/docs/auth_connect_compatibility.md
- Migration guide: https://github.com/Cap-go/capacitor-social-login/blob/main/MIGRATION_AUTH_CONNECT.md
- Keycloak setup: https://github.com/Cap-go/capacitor-social-login/blob/main/docs/setup_keycloak.md
Best experience to read the doc here:
https://capgo.app/docs/plugins/social-login/getting-started/
| Plugin version | Capacitor compatibility | Maintained |
|---|---|---|
| v8.*.* | v8.*.* | ✅ |
| v7.*.* | v7.*.* | On demand |
| v6.*.* | v6.*.* | ❌ |
| v5.*.* | v5.*.* | ❌ |
Note: The major version of this plugin follows the major version of Capacitor. Use the version that matches your Capacitor installation (e.g., plugin v8 for Capacitor 8). Only the latest major version is actively maintained.
You can use our AI-Assisted Setup to install the plugin. Add the Capgo skills to your AI tool using the following command:
npx skills add https://github.com/cap-go/capacitor-skills --skill capacitor-pluginsThen use the following prompt:
Use the `capacitor-plugins` skill from `cap-go/capacitor-skills` to install the `@capgo/capacitor-social-login` plugin in my project.
If you prefer Manual Setup, install the plugin by running the following commands and follow the platform-specific instructions below:
npm install @capgo/capacitor-social-login
npx cap syncYou can configure which providers to include to reduce app size. This is especially useful if you only need specific providers.
Add provider configuration to your capacitor.config.ts:
import type { CapacitorConfig } from '@capacitor/cli';
const config: CapacitorConfig = {
appId: 'com.example.app',
appName: 'MyApp',
webDir: 'dist',
plugins: {
SocialLogin: {
providers: {
google: true, // true = enabled (bundled), false = disabled (not bundled)
facebook: true, // Use false to reduce app size
apple: true, // Apple uses system APIs only (no third-party networking dependency)
twitter: false // false = disabled (not bundled)
},
logLevel: 1 // Warnings and errors only
}
}
};
export default config;true(default): Provider is enabled - dependencies are bundled in final APK/IPAfalse: Provider is disabled - dependencies are not bundled in final APK/IPA
- Changes require running
npx cap syncto take effect - If configuration is not provided, all providers default to
true(enabled, backward compatible) - Important: Disabling a provider (
false) will make it unavailable at runtime, regardless of whether it actually adds any dependencies. The provider will be disabled even if it uses only system APIs. - This configuration only affects iOS and Android platforms; it does not affect the web platform.
- Important: Using
falsemeans the dependency won't be bundled, but the plugin code still compiles against it. Ensure the consuming app includes the dependency if needed. - Facebook: When
facebook: false, the Facebook SDK is omitted and the plugin compiles a provider stub in its own package, nocom.facebook.*classes are shipped (avoids privacy-scanner false positives). - Apple (iOS):
apple: trueenables Sign in with Apple (AuthenticationServices). Redirect URL and backend token exchange use Foundation URLSession, so no third-party networking library is required.apple: falsedisables Apple authentication at runtime, including basic Sign in with Apple, consistent with the rule above thatfalseproviders are unavailable at runtime. - Apple Sign-In on Android uses OAuth flow without external SDK dependencies
- Twitter uses standard OAuth 2.0 flow without external SDK dependencies
To only include Google Sign-In and disable others:
plugins: {
SocialLogin: {
providers: {
google: true, // Enabled
facebook: false, // Disabled (not bundled)
apple: true, // Enabled
twitter: false // Disabled (not bundled)
}
}
}How to get the credentials How to setup redirect url
For android you need a server to get the callback from the apple login. As we use the web SDK .
Call the initialize method with the apple provider
await SocialLogin.initialize({
apple: {
clientId: 'your-client-id',
redirectUrl: 'your-redirect-url',
},
});
const res = await SocialLogin.login({
provider: 'apple',
options: {
scopes: ['email', 'name'],
},
});call the initialize method with the apple provider
await SocialLogin.initialize({
apple: {
clientId: 'your-client-id', // it not used at os level only in plugin to know which provider initialize
},
});
const res = await SocialLogin.login({
provider: 'apple',
options: {
scopes: ['email', 'name'],
},
});Docs: How to setup facebook login
📘 Complete Facebook Business Login Guide - Learn how to access Instagram, Pages, and business features
This plugin fully supports Facebook Business Login for accessing business-related features and permissions. Business accounts can request additional permissions beyond standard consumer login, including Instagram and Pages management.
Works on iOS, Android, and Web. After login, use providerSpecificCall to fetch business fields (e.g., instagram_business_account, Pages) on every platform.
Supported Business Permissions:
instagram_basic- Access to Instagram Basic Display APIinstagram_manage_insights- Access to Instagram Insightspages_show_list- List of Pages the person managespages_read_engagement- Read engagement data from Pagespages_manage_posts- Manage posts on Pagesbusiness_management- Manage business assets- And many more - see Facebook Permissions Reference
Configuration Requirements:
- Your Facebook app must be configured as a Business app in the Facebook Developer Console
- Business permissions may require Facebook's App Review before production use
- Your app must comply with Facebook's Business Use Case policies
Example - Instagram Basic Access:
await SocialLogin.initialize({
facebook: {
appId: 'your-business-app-id',
clientToken: 'your-client-token',
},
});
const res = await SocialLogin.login({
provider: 'facebook',
options: {
permissions: [
'email',
'public_profile',
'instagram_basic', // Instagram account info
'pages_show_list', // List of managed Pages
'pages_read_engagement' // Page engagement data
],
},
});
// Access Instagram data through Facebook Graph API
const profile = await SocialLogin.providerSpecificCall({
call: 'facebook#getProfile',
options: {
fields: ['id', 'name', 'email', 'instagram_business_account'],
},
});Example - Pages Management:
const res = await SocialLogin.login({
provider: 'facebook',
options: {
permissions: [
'email',
'pages_show_list',
'pages_manage_posts',
'pages_read_engagement',
],
},
});
// Fetch user's managed pages with Instagram accounts
const profile = await SocialLogin.providerSpecificCall({
call: 'facebook#getProfile',
options: {
fields: ['id', 'name', 'accounts{id,name,instagram_business_account}'],
},
});Important Notes:
- Testing: You can test business permissions with test users and development apps without App Review
- Production: Most business permissions require Facebook App Review before going live
- Rate Limits: Business APIs have different rate limits - review Facebook's documentation
- Setup: Follow Facebook Business Integration Guide
More information can be found here: https://developers.facebook.com/docs/android/getting-started
Then call the initialize method with the facebook provider
await SocialLogin.initialize({
facebook: {
appId: 'your-app-id',
clientToken: 'your-client-token',
},
});
const res = await SocialLogin.login({
provider: 'facebook',
options: {
permissions: ['email', 'public_profile'],
},
});Every app, with or without UIScene, needs these settings. Add the following in the ios/App/App/Info.plist file inside the outermost <dict>.
If Info.plist already has a CFBundleURLTypes key (for example from the Google setup), do not add a second one. Append only the Facebook <dict> (the one with fb[APP_ID]) to the existing CFBundleURLTypes array and keep every existing URL type, otherwise another provider's callback scheme can stop working.
The same applies to LSApplicationQueriesSchemes: if it already exists, do not add a second key. Append the Facebook <string> entries to the existing array and keep every existing scheme, otherwise canOpenURL checks for other integrations can stop working.
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>fb[APP_ID]</string>
</array>
</dict>
</array>
<key>FacebookAppID</key>
<string>[APP_ID]</string>
<key>FacebookClientToken</key>
<string>[CLIENT_TOKEN]</string>
<key>FacebookDisplayName</key>
<string>[APP_NAME]</string>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>fbapi</string>
<string>fbauth</string>
<string>fb-messenger-share-api</string>
<string>fbauth2</string>
<string>fbshareextension</string>
</array>More information can be found here: https://developers.facebook.com/docs/facebook-login/ios
If your app uses UIApplicationSceneManifest (Capacitor 8.5+ / npx cap migrate), URL opens go to SceneDelegate.swift. Keep Facebook SDK startup in AppDelegate.application(_:didFinishLaunchingWithOptions:), and forward all URL contexts to SceneDelegateProxy in scene(_:openURLContexts:). Do not also call the Facebook SDK URL handler in SceneDelegate, or the URL reaches the SDK twice.
AppDelegate.swift (required for UIScene apps too; Facebook SDK still initializes at launch):
import UIKit
import Capacitor
import FBSDKCoreKit
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FBSDKCoreKit.ApplicationDelegate.shared.application(
application,
didFinishLaunchingWithOptions: launchOptions
)
return true
}SceneDelegate.swift (URL opens only; no direct Facebook SDK calls):
import UIKit
import Capacitor
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
// Forward every context. SceneDelegateProxy posts capacitorOpenURL, and this
// plugin's observer passes the URL to the Facebook SDK exactly once.
SceneDelegateProxy.shared.scene(scene, openURLContexts: URLContexts)
}This plugin calls the Facebook SDK URL handler when it receives Capacitor's capacitorOpenURL notification (custom schemes) and capacitorOpenUniversalLink (HTTPS App Links from scene(_:continue:)), so direct Facebook SDK calls in SceneDelegate are not needed. Forwarding every URL context to SceneDelegateProxy is still required: without it, capacitorOpenURL is never posted and the plugin never sees the callback.
In file ios/App/App/AppDelegate.swift add or replace the following:
import UIKit
import Capacitor
import FBSDKCoreKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FBSDKCoreKit.ApplicationDelegate.shared.application(
application,
didFinishLaunchingWithOptions: launchOptions
)
return true
}
...
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
// Forward every URL so Capacitor posts capacitorOpenURL. This plugin's observer calls the Facebook SDK handler.
return ApplicationDelegateProxy.shared.application(app, open: url, options: options)
}
}Then call the initialize method with the facebook provider
await SocialLogin.initialize({
facebook: {
appId: 'your-app-id',
},
});
const res = await SocialLogin.login({
provider: 'facebook',
options: {
permissions: ['email', 'public_profile'],
},
});For Google login to work properly across all platforms, you need different client IDs and must understand the requirements for each mode:
await SocialLogin.initialize({
google: {
webClientId: 'YOUR_WEB_CLIENT_ID', // Required for Android and Web
iOSClientId: 'YOUR_IOS_CLIENT_ID', // Required for iOS
iOSServerClientId: 'YOUR_WEB_CLIENT_ID', // Required for iOS offline mode and server authorization (same as webClientId)
mode: 'online', // 'online' or 'offline'
}
});Important Notes:
webClientId: Required for Android and Web platformsiOSClientId: Required for iOS platformiOSServerClientId: Required when usingmode: 'offline'on iOS or when you need to verify the token on the server (should be the same value aswebClientId)mode: 'offline': Returns onlyserverAuthCodefor backend authentication, no user profile data, andrefresh()is not available in-app. ExchangeserverAuthCodeon your backend and refresh there.mode: 'online': Returns user profile data and access tokens (default). On Android, default online login still runsAuthorizationClientand returns anaccessTokenwhen Google provides one. SetskipAuthOnlyAuthorizationAfterSignIn: trueininitialize()if authorize hangs on stockBridgeActivity, or if login rejects because authorization needs user interaction that stockBridgeActivitycannot route (thenaccessTokenmay benull; useidTokenfor auth).
The implementation use the new library of Google who use Google account at Os level, make sure your device does have at least one google account connected
Call the initialize method with the google provider:
await SocialLogin.initialize({
google: {
webClientId: 'your-web-client-id', // Required: the web client id for Android and Web
},
});
const res = await SocialLogin.login({
provider: 'google',
options: {},
});Optional hang workaround on stock BridgeActivity (skips authorize; accessToken may be null):
await SocialLogin.initialize({
google: {
webClientId: 'your-web-client-id',
skipAuthOnlyAuthorizationAfterSignIn: true,
},
});Custom Google API scopes on Android require a modified MainActivity that implements ModifiedMainActivityForSocialLoginPlugin and forwards onActivityResult to the plugin (see example-app/android/.../MainActivity.java). On a stock BridgeActivity, do not pass a scopes array to login(); even ['email', 'profile'] is rejected because those scopes are already included by default.
// Only after MainActivity implements ModifiedMainActivityForSocialLoginPlugin:
const resWithScopes = await SocialLogin.login({
provider: 'google',
options: {
scopes: ['https://www.googleapis.com/auth/drive.readonly'],
},
});// Misleading on stock BridgeActivity (will reject at runtime):
// await SocialLogin.login({ provider: 'google', options: { scopes: ['email', 'profile'] } });On Android this plugin uses Google Credential Manager (androidx.credentials + Sign in with Google), not the legacy GoogleSignInClient API. Logcat errors such as GetCredentialCustomException: [28444] Developer console is not set up correctly come from that stack.
Filter Logcat with GoogleProvider or CapgoSocialLogin after a failed login. The plugin logs your package name, signing SHA-1, and a masked webClientId to help compare against Google Cloud Console.
You need two kinds of OAuth 2.0 client IDs:
| Client type | Used for | Where it goes |
|---|---|---|
| Web application | Server / ID token audience | webClientId in SocialLogin.initialize() |
| Android (one per signing key) | Proves your APK is allowed to call Google | Google Cloud Console only, do not pass this ID to webClientId |
Common mistake: using the Android client ID as webClientId. Credential Manager requires the Web client ID there. The Android client only needs the correct package name + SHA-1 registered in the console.
Create one Android OAuth client for each certificate that signs builds you test:
- Debug, from
./gradlew signingReport(debug variant) - Release, from the APK/AAB you actually install (see below)
- Play App Signing, from Play Console → App integrity → App signing key certificate (required for Play Store builds even if your upload key SHA-1 is already registered)
The applicationId in android/app/build.gradle must match the Android OAuth client package name exactly (including any .debug suffix if you use one).
If the OAuth consent screen is in Testing mode, add every Google account you test with under Audience → Test users. Publishing the app to Production is not required for email / profile scopes. Digital Asset Links (assetlinks.json) are not required for Sign in with Google via Credential Manager.
Google Cloud changes can take up to a few hours to propagate; a device restart alone may not be enough.
This almost always means Google rejected the combination of installed APK signing certificate, package name, and **webClientId`. Work through this checklist:
- Confirm
webClientIdis the Web application client ID (ends with.apps.googleusercontent.com). - Run the app, reproduce the failure, and read Logcat (
GoogleProvider) forsigningSha1=andpackage=. - In Google Cloud Console → Credentials, open your Android OAuth client and verify that exact package name and SHA-1 are listed.
- If testing a release build, register the SHA-1 from that build, not only the debug keystore.
- If the app is distributed via Play Store, also register the Play App Signing SHA-1.
- Ensure Web and Android clients live in the same Google Cloud project.
- If consent screen is in Testing, confirm the Google account is a test user.
- Wait and retry after console changes.
USER_CANCELLED after picking an account on a misconfigured debug build can still be a SHA-1 / client-ID mismatch, fix the console setup above first.
This error comes from Google Credential Manager when re-authenticating a cached Google account fails. It often affects only some users on the same build while others sign in normally.
Automatic recovery: On the first [16] failure, the plugin clears Credential Manager credential-selection state and retries once with the standard sign-in UI (filterByAuthorizedAccounts: false). No app code change is required for this retry.
If the retry still fails for specific users, check:
- OAuth consent screen, must be External (Internal / Workspace-only blocks consumer
@gmail.comaccounts). - Testing mode, every failing Google account must be listed under Audience → Test users.
- Sign in with Google setting, the user may have disabled your app under Google Account → Sign in with Google.
- Family Link / supervised accounts, ensure
filterByAuthorizedAccountsis not explicitly set totrue(the default isfalse; see Family Link section below). - Play App Signing SHA-1, still required for Play Store builds even when most users succeed (some device/account paths are stricter).
- Explicit override, if your app sets
filterByAuthorizedAccounts: true, set it back tofalsefor affected users; the default already skips authorized-account filtering.
After a failure, filter Logcat for GoogleProvider, the plugin logs package, signingSha1, and webClientId.
Debug / local builds:
cd android && ./gradlew signingReportSigned release APK:
keytool -printcert -jarfile android/app/release/app-release.apkThen add that SHA-1 to an Android OAuth client (package name + SHA-1) in Google Cloud Console, reinstall the same signed APK, and test again:
adb install android/app/release/app-release.apkTokens are nested under result:
const login = await SocialLogin.login({ provider: 'google' });
const idToken = login.result?.idToken; // not login.idTokenFor Firebase Auth, create credentials with that idToken and use the Web Client ID as webClientId in initialize.
Call the initialize method with the google provider:
await SocialLogin.initialize({
google: {
iOSClientId: 'your-ios-client-id', // Required: the iOS client id
iOSServerClientId: 'your-web-client-id', // Required for offline mode: same as webClientId
mode: 'online', // 'online' for user data, 'offline' for server auth code only
},
});
const res = await SocialLogin.login({
provider: 'google',
options: {
scopes: ['email', 'profile'],
},
});Google Sign-In completes through a custom URL scheme callback. On Capacitor 8.5+ with the UIScene lifecycle, that callback is delivered to SceneDelegate.scene(_:openURLContexts:), not AppDelegate.application(_:open:options:). See docs/setup_google.md for the SceneDelegate.swift snippet.
Automatic handling: This plugin listens for Capacitor's capacitorOpenURL notification (posted from both AppDelegate and SceneDelegate paths) and calls GIDSignIn.sharedInstance.handle(url) when the Google Sign-In SDK is linked. Direct GIDSignIn.sharedInstance.handle(url) calls in SceneDelegate or AppDelegate are not needed once SocialLogin.initialize() runs. Forwarding URL opens to SceneDelegateProxy (UIScene) or ApplicationDelegateProxy (AppDelegate) is still required, since that is what posts capacitorOpenURL.
Offline Mode Behavior:
When using mode: 'offline', the login response will only contain:
{
provider: 'google',
result: {
serverAuthCode: 'auth_code_for_backend',
responseType: 'offline'
}
// Note: No user profile data is returned in offline mode
}serverAuthCode is for your backend. In offline mode you should exchange it on your server for access and refresh tokens, then refresh those tokens on the server side. Calling SocialLogin.refresh({ provider: 'google' ... }) is not supported in offline mode.
Initialize method to create a script tag with Google lib. We cannot know when it's ready so be sure to do it early in web otherwise it will fail.
On Web, Google refresh() is not implemented, even when using mode: 'online'. Call SocialLogin.login({ provider: 'google', ... }) again to obtain a fresh token.
Telegram uses the Login Widget (oauth.telegram.org), not standard OAuth2. Create a bot with @BotFather, set the domain for the widget, and pass the bot id (not the bot token):
await SocialLogin.initialize({
telegram: {
botId: '123456789',
redirectUrl: 'https://your-app.example/auth/telegram', // or myapp://telegram-auth on native
// Required on native when redirectUrl is a custom scheme
origin: 'https://your-app.example',
requestAccess: 'write',
},
});
const res = await SocialLogin.login({
provider: 'telegram',
options: {},
});
// Verify `res.result.hash` on your backend with the bot token.
// Reject stale or future `res.result.authDate` values before creating a session.
// Never ship the bot token in the app.
console.log(res.result.profile.id, res.result.hash);LinkedIn is a convenience wrapper around the generic OAuth2 engine (OpenID Connect userinfo).
Register a web app in the LinkedIn Developer Portal with the Sign In with LinkedIn using OpenID Connect product, then:
await SocialLogin.initialize({
linkedin: {
clientId: 'your-linkedin-client-id',
redirectUrl: 'https://your-app.example/auth/linkedin',
// Optional: only if your LinkedIn app is a confidential client
// clientSecret: 'your-linkedin-client-secret',
},
});
const res = await SocialLogin.login({
provider: 'linkedin',
options: {
// defaults to 'openid profile email'
},
});
console.log(res.result.accessToken?.token);
console.log(res.result.resourceData); // LinkedIn userinfo payloadYou can still configure LinkedIn yourself via oauth2.linkedin if you need custom endpoints.
TikTok Login Kit is a convenience wrapper around the generic OAuth2 engine. The plugin sends client_key (not client_id) and uses TikTok's v2 authorize/token endpoints. Login exchanges the authorization code in the plugin and does not return that code for backend exchange.
Create a TikTok developer app, enable Login Kit, and register your redirect URL, then:
await SocialLogin.initialize({
tiktok: {
clientKey: 'your-tiktok-client-key',
redirectUrl: 'https://your-app.example/auth/tiktok',
// Optional confidential-client secret; prefer PKCE for public apps
// clientSecret: 'your-tiktok-client-secret',
},
});
const res = await SocialLogin.login({
provider: 'tiktok',
options: {
// defaults to 'user.info.basic'
},
});
console.log(res.result.accessToken?.token);You can still configure TikTok yourself via oauth2 plus clientIdParamName: 'client_key'.
The plugin supports generic OAuth2 authentication, allowing you to integrate with any OAuth2-compliant provider (GitHub, Azure AD, Auth0, Okta, Keycloak, custom servers, etc.). You can configure multiple OAuth2 providers simultaneously.
For Keycloak, use the generic OAuth2 provider with your realm issuer URL. See the Keycloak setup guide.
await SocialLogin.initialize({
oauth2: {
// GitHub 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,
},
// Azure AD 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',
pkceEnabled: true,
resourceUrl: 'https://graph.microsoft.com/v1.0/me',
},
// Auth0 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',
},
},
},
});If you want the same provider names as Ionic Auth Connect, use the preset wrapper. It maps those providers to the existing OAuth2 engine.
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',
},
},
});
const auth0Result = await SocialLoginAuthConnect.login({
provider: 'auth0',
});Notes:
- Presets can be overridden: any
oauth2entry with the same provider key (for example,oauth2: { auth0: ... }) overrides the preset for that provider. - If your provider uses non-standard endpoints, override
authorizationBaseUrl,accessTokenEndpoint,resourceUrl, orlogoutUrlin the preset.
// Login with GitHub
const githubResult = await SocialLogin.login({
provider: 'oauth2',
options: {
providerId: 'github', // Required: must match key from initialize()
},
});
// Login with Azure AD
const azureResult = await SocialLogin.login({
provider: 'oauth2',
options: {
providerId: 'azure',
scope: 'openid profile email', // Optional: override default scopes
},
});
console.log('Access Token:', azureResult.result.accessToken?.token);
console.log('ID Token:', azureResult.result.idToken);
console.log('User Data:', azureResult.result.resourceData);const status = await SocialLogin.isLoggedIn({
provider: 'oauth2',
providerId: 'github', // Required for OAuth2
});
console.log('Is logged in:', status.isLoggedIn);await SocialLogin.logout({
provider: 'oauth2',
providerId: 'github', // Required for OAuth2
});await SocialLogin.refresh({
provider: 'oauth2',
options: {
providerId: 'github', // Required for OAuth2
},
});| Option | Type | Required | Description |
|---|---|---|---|
appId |
string | Yes | OAuth2 Client ID |
issuerUrl |
string | No* | OpenID Connect issuer URL for discovery (*Use this or an authorization endpoint) |
authorizationBaseUrl / authorizationEndpoint |
string | No* | Authorization endpoint URL aliases for the same setting (*Use one alias or issuerUrl) |
accessTokenEndpoint / tokenEndpoint |
string | No* | Token endpoint URL aliases for the same setting (*Required for code flow without issuerUrl) |
redirectUrl |
string | Yes | Callback URL for OAuth redirect |
responseType |
'code' | 'token' | No | OAuth flow type (default: 'code') |
pkceEnabled |
boolean | No | Enable PKCE (default: true) |
scope |
string | No | Default scopes to request |
resourceUrl |
string | No | URL to fetch user profile after auth |
additionalParameters |
Record<string, string> | No | Extra params for authorization URL |
additionalResourceHeaders |
Record<string, string> | No | Extra headers for resource request |
logoutUrl |
string | No | URL to open on logout |
androidUseCustomTabs |
boolean | No | Android-only: use Chrome Custom Tabs instead of WebView (default: false). Requires a deep-linkable redirectUrl |
logsEnabled |
boolean | No | Enable debug logging (default: false) |
iOS: Uses ASWebAuthenticationSession for secure authentication.
Android: Uses an embedded WebView by default. Set androidUseCustomTabs: true to use Chrome Custom Tabs instead (RFC 8252 / system browser). Custom Tabs require a custom-scheme or App Link redirectUrl with a matching intent filter in your app's AndroidManifest.xml, and android:launchMode="singleTask" (or singleTop) on the main activity so redirects arrive via onNewIntent.
Web: Opens a popup window for OAuth flow.
- Always use PKCE (
pkceEnabled: true) for public clients - Use authorization code flow (
responseType: 'code') instead of implicit flow - Store tokens securely using @capgo/capacitor-persistent-account
- Use HTTPS for all endpoints and redirect URLs in production
Use openAuthSession() when your app already has an authorize URL (from your IdP, OutSystems, Keycloak, Azure AD, etc.) and you only need a system browser session that returns the full redirect callback URL. You keep token exchange and session management in your own code.
Use case: Enterprise SSO or OIDC where the login page URL is built server-side or with your SDK, and mobile must reuse the platform secure browser (Custom Tabs / ASWebAuthenticationSession) instead of an embedded WebView.
import { SocialLogin } from '@capgo/capacitor-social-login';
const authorizeUrl =
'https://login.example.com/oauth2/authorize?client_id=APP&redirect_uri=myapp%3A%2F%2Fauth%2Fcallback&response_type=code&state=xyz';
try {
const { callbackURL } = await SocialLogin.openAuthSession({
url: authorizeUrl,
callbackURLScheme: 'myapp',
prefersEphemeralSession: false, // iOS: allow shared SSO cookies when false
});
// callbackURL e.g. myapp://auth/callback?code=...&state=...
const parsed = new URL(callbackURL.replace('myapp://', 'https://placeholder/'));
const code = parsed.searchParams.get('code');
} catch (error) {
if ((error as { code?: string }).code === 'USER_CANCELLED') {
// user closed the browser tab or cancelled the sheet
}
}On web, host a small redirect page that posts the final URL to a BroadcastChannel (same pattern as openSecureWindow()). Default channel name for openAuthSession is capgo-auth-session.
iOS: Register your callback URL scheme in Info.plist (CFBundleURLTypes / CFBundleURLSchemes). callbackURLScheme must match that scheme (without ://).
Android: Add an intent filter on your main activity for the redirect URI scheme and host, and use launchMode singleTask or singleTop so the redirect arrives in onNewIntent:
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="myapp" android:host="auth" android:pathPrefix="/callback" />
</intent-filter>On web, the plugin opens the authorize URL in a popup via window.open. Call openAuthSession() from a user gesture (button click). Popup blockers must allow your origin, or the call fails immediately with an error about popups.
Host an HTTPS redirect page on the same origin as your app (BroadcastChannel only delivers to pages that share the app's origin). Register that URL with your IdP. The landing page can post location.href when the authorize URL includes the same redirect_uri, or post a ${callbackURLScheme}://... string for prefix matching:
<script>
// Option A: post the HTTPS callback (works when redirect_uri is in the authorize URL)
new BroadcastChannel('capgo-auth-session').postMessage(location.href);
window.close();
</script>See also openSecureWindow() for the legacy option names (authEndpoint, redirectUri, redirectedUri).
If you get this error on App Store Connect:
ITMS-91056: Invalid privacy manifest - The PrivacyInfo.xcprivacy file from the following path is invalid: ...
How to fix:
- Make sure your app's
PrivacyInfo.xcprivacyis valid JSON, with only Apple-documented keys/values. - Do not include a privacy manifest in the plugin, only in your app.
Problem: After submitting your app to Google Play, you receive this error:
Google Api Error: Invalid request - This release includes the com.google.android.gms.permission.AD_ID permission
but your declaration on Play Console says your app doesn't use advertising ID.
Root Cause: The Facebook SDK includes AD_ID and other advertising-related permissions.
Solution: If you're not using Facebook login, set facebook: false in your capacitor.config.ts:
const config: CapacitorConfig = {
plugins: {
SocialLogin: {
providers: {
google: true,
facebook: false, // Completely excludes Facebook SDK and its permissions
apple: true,
},
},
},
};Then run npx cap sync. The plugin uses stub classes instead of the real Facebook SDK, so no Facebook dependencies or permissions are included in your build.
On Android, this error comes from Google Credential Manager when the installed APK's signing certificate, package name, or webClientId does not match Google Cloud Console.
See Android troubleshooting (Credential Manager, SHA-1, and Firebase) for the full checklist. After a failed login, filter Logcat for GoogleProvider, the plugin prints package, signingSha1, and webClientId to compare with your OAuth clients.
Credential Manager returns this when re-authenticating a previously used Google account fails. It can affect a subset of users on the same app version.
The plugin automatically clears Credential Manager credential-selection state and retries once with the standard account picker. If login still fails for specific accounts, see the [16] Account reauth failed subsection under Android troubleshooting (OAuth consent External vs Internal, test users, Family Link, Sign in with Google account setting).
Problem: When users try to sign in with Google accounts supervised by Family Link, login fails with:
NoCredentialException: No credentials available
or, in some cases:
[16] Account reauth failed
Root Cause: Family Link supervised accounts have different authentication requirements and may not work properly with certain Google Sign-In configurations.
Solution: When implementing Google Sign-In for apps that need to support Family Link accounts, use the following configuration:
import { SocialLogin } from '@capacitor/social-login';
// For Family Link accounts, disable filtering by authorized accounts
await SocialLogin.login({
provider: 'google',
options: {
style: 'bottom', // or 'standard'
filterByAuthorizedAccounts: false, // Important for Family Link (default is false; set explicitly when using bottom UI)
scopes: ['profile', 'email']
}
});Key Points:
- Do not set
filterByAuthorizedAccountstotruewhen supporting Family Link accounts (default isfalse) - The plugin will automatically retry with 'standard' style if 'bottom' style fails with NoCredentialException
- These options only affect Android; iOS handles Family Link accounts normally
- The error message will suggest disabling
filterByAuthorizedAccountsif login fails
Note: Other apps like Listonic work with Family Link accounts because they use similar configurations. The default settings may be too restrictive for supervised accounts.
You can use the @capgo/capacitor-persistent-account plugin for this.
This plugin stores data in secure locations for native devices.
For Android, it will store data in Android's Account Manager, which provides system-level account management. For iOS, it will store data in the Keychain, which is Apple's secure credential storage.
initialize(...)login(...)logout(...)isLoggedIn(...)getAuthorizationCode(...)refresh(...)refreshToken(...)handleRedirectCallback()decodeIdToken(...)getAccessTokenExpirationDate(...)isAccessTokenAvailable(...)isAccessTokenExpired(...)isRefreshTokenAvailable(...)providerSpecificCall(...)getPluginVersion()openSecureWindow(...)openAuthSession(...)- Interfaces
- Type Aliases
initialize(options: InitializeOptions) => Promise<void>Initialize the plugin
| Param | Type |
|---|---|
options |
InitializeOptions |
login<T extends "apple" | "google" | "facebook" | "twitter" | "linkedin" | "tiktok" | "oauth2" | "telegram">(options: Extract<LoginOptions, { provider: T; }>) => Promise<{ provider: T; result: ProviderResponseMap[T]; }>Login with the selected provider
| Param | Type |
|---|---|
options |
Extract<{ provider: 'facebook'; options: FacebookLoginOptions; }, { provider: T; }> | Extract<{ provider: 'google'; options: GoogleLoginOptions; }, { provider: T; }> | Extract<{ provider: 'apple'; options: AppleProviderOptions; }, { provider: T; }> | Extract<{ provider: 'twitter'; options: TwitterLoginOptions; }, { provider: T; }> | Extract<{ provider: 'telegram'; options: TelegramLoginOptions; }, { provider: T; }> | Extract<{ provider: 'linkedin'; options: LinkedInLoginOptions; }, { provider: T; }> | Extract<{ provider: 'tiktok'; options: TikTokLoginOptions; }, { provider: T; }> | Extract<{ provider: 'oauth2'; options: OAuth2LoginOptions; }, { provider: T; }> |
Returns: Promise<{ provider: T; result: ProviderResponseMap[T]; }>
logout(options: { provider: 'apple' | 'google' | 'facebook' | 'twitter' | 'telegram' | 'linkedin' | 'tiktok' | 'oauth2'; providerId?: string; clearCachedUserInfo?: boolean; }) => Promise<void>Logout
| Param | Type |
|---|---|
options |
{ provider: 'apple' | 'google' | 'facebook' | 'twitter' | 'linkedin' | 'tiktok' | 'oauth2' | 'telegram'; providerId?: string; clearCachedUserInfo?: boolean; } |
isLoggedIn(options: isLoggedInOptions) => Promise<{ isLoggedIn: boolean; }>IsLoggedIn
| Param | Type |
|---|---|
options |
isLoggedInOptions |
Returns: Promise<{ isLoggedIn: boolean; }>
getAuthorizationCode(options: AuthorizationCodeOptions) => Promise<AuthorizationCode>Get the current authorization code
| Param | Type |
|---|---|
options |
AuthorizationCodeOptions |
Returns: Promise<AuthorizationCode>
refresh(options: LoginOptions) => Promise<void>Refresh the access token for the logged-in provider.
Google Android refresh behavior:
On Android, when the saved ID token is still valid and either no access token is stored or Google access
token validation succeeds within the timeout, refresh() resolves without updating either token. That
early return applies regardless of skipAuthOnlyAuthorizationAfterSignIn.
If validation fails or times out, refresh() continues even when a token remains stored; with
skipAuthOnlyAuthorizationAfterSignIn: true and default OIDC scopes, a successful credential refresh
then clears that access token without obtaining a new one.
Google Offline Mode Limitation:
This method is NOT supported when Google is initialized with mode: 'offline'.
Offline mode only returns serverAuthCode for backend token exchange, so token refresh must happen on your backend.
The plugin logs and rejects with a message explaining that you should send serverAuthCode to your backend,
refresh the Google tokens there, or switch to mode: 'online' for client-side refresh.
Google Android skipAuthOnlyAuthorizationAfterSignIn:
When initialize sets google.skipAuthOnlyAuthorizationAfterSignIn: true and only default OIDC scopes are
requested, a refresh that runs past the early return skips AuthorizationClient.authorize(), updates the
saved idToken, and clears any saved access token; no new access token is obtained. Enabling the option
does not clear a stored access token while the early return applies (validation succeeded or no token
stored). With default false, refresh still skips authorize on the early return when no access token is
stored but the ID token is valid.
Google Web Limitation:
On Web, Google refresh() is not implemented, even when using mode: 'online'.
Call login() again on Web to obtain a fresh token instead.
| Param | Type |
|---|---|
options |
LoginOptions |
refreshToken(options: RefreshTokenOptions) => Promise<OAuth2LoginResponse>OAuth2 refresh-token helper (feature parity with Capawesome OAuth).
Scope:
- Applies to the built-in
oauth2provider and the LinkedIn and TikTok convenience wrappers. - Requires a token endpoint (either
accessTokenEndpoint/tokenEndpointorissuerUrldiscovery).
Security note:
- This does not validate JWT signatures. It only exchanges/refreshes tokens.
If refreshToken is omitted, the plugin will attempt to use the stored refresh token (if available).
| Param | Type |
|---|---|
options |
RefreshTokenOptions |
Returns: Promise<OAuth2LoginResponse>
handleRedirectCallback() => Promise<LoginResult | null>Web-only: handle the OAuth redirect callback and return the parsed result.
Notes:
- This is only meaningful on Web. iOS/Android implementations will reject.
- Intended for redirect-based flows (e.g.
oauth2withflow: 'redirect') where the page navigates away. - LinkedIn convenience logins (
provider: 'linkedin',flow: 'redirect') returnprovider: 'linkedin'. The same app used asoauth2withproviderId: 'linkedin'keepsprovider: 'oauth2'.
Returns: Promise<LoginResult | null>
decodeIdToken(options: { idToken?: string; token?: string; }) => Promise<{ claims: Record<string, any>; }>Decode a JWT (typically an OIDC ID token) into its claims.
Notes:
- Accepts both
idTokenandtokento match common naming (Capawesome usestoken). - This does not validate the signature or issuer/audience. It only base64url-decodes the payload.
email_verified semantics by provider (for account linking):
- Google — ID token includes
email_verified(boolean). Whentrue, Google attests the user controls that email. Verify the JWT on your backend before trusting it. - Apple — ID token includes
email_verified(boolean). Whentrue, Apple attests the user controls that email (including private relay). Verify the JWT on your backend. - Meta (Facebook) — Limited Login OIDC tokens may include
emailbut do not includeemail_verified. The presence ofemailis not the same guarantee asemail_verified: truefrom Google or Apple. Do not link accounts by email across providers using Meta claims alone; perform your own email verification if needed.
| Param | Type |
|---|---|
options |
{ idToken?: string; token?: string; } |
Returns: Promise<{ claims: Record<string, any>; }>
getAccessTokenExpirationDate(options: { accessTokenExpirationDate: number; }) => Promise<{ date: string; }>Convert an access token expiration timestamp (milliseconds since epoch) to an ISO date string.
This is a pure helper (feature parity with Capawesome OAuth) and does not depend on provider state.
| Param | Type |
|---|---|
options |
{ accessTokenExpirationDate: number; } |
Returns: Promise<{ date: string; }>
isAccessTokenAvailable(options: { accessToken: string | null; }) => Promise<{ isAvailable: boolean; }>Check if an access token is available (non-empty).
This is a pure helper (feature parity with Capawesome OAuth) and does not depend on provider state.
| Param | Type |
|---|---|
options |
{ accessToken: string | null; } |
Returns: Promise<{ isAvailable: boolean; }>
isAccessTokenExpired(options: { accessTokenExpirationDate: number; }) => Promise<{ isExpired: boolean; }>Check if an access token is expired.
This is a pure helper (feature parity with Capawesome OAuth) and does not depend on provider state.
| Param | Type |
|---|---|
options |
{ accessTokenExpirationDate: number; } |
Returns: Promise<{ isExpired: boolean; }>
isRefreshTokenAvailable(options: { refreshToken: string | null; }) => Promise<{ isAvailable: boolean; }>Check if a refresh token is available (non-empty).
This is a pure helper (feature parity with Capawesome OAuth) and does not depend on provider state.
| Param | Type |
|---|---|
options |
{ refreshToken: string | null; } |
Returns: Promise<{ isAvailable: boolean; }>
providerSpecificCall<T extends ProviderSpecificCall>(options: { call: T; options: ProviderSpecificCallOptionsMap[T]; }) => Promise<ProviderSpecificCallResponseMap[T]>Execute provider-specific calls
| Param | Type |
|---|---|
options |
{ call: T; options: ProviderSpecificCallOptionsMap[T]; } |
Returns: Promise<ProviderSpecificCallResponseMap[T]>
getPluginVersion() => Promise<{ version: string; }>Get the native Capacitor plugin version
Returns: Promise<{ version: string; }>
openSecureWindow(options: OpenSecureWindowOptions) => Promise<OpenSecureWindowResponse>Opens a secured window for OAuth2 authentication. For web, you should have the code in the redirected page to use a broadcast channel to send the redirected url to the app Something like:
<html>
<head></head>
<body>
<script>
const searchParams = new URLSearchParams(location.search)
if (searchParams.has("code")) {
new BroadcastChannel("my-channel-name").postMessage(location.href);
window.close();
}
</script>
</body>
</html>For mobile, you should have a redirect uri that opens the app, something like: myapp://oauth_callback/
And make sure to register it in the app's info.plist:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>myapp</string>
</array>
</dict>
</array>And in the AndroidManifest.xml file:
<activity>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:host="oauth_callback" android:scheme="myapp" />
</intent-filter>
</activity>| Param | Type | Description |
|---|---|---|
options |
OpenSecureWindowOptions |
- the options for the openSecureWindow call |
Returns: Promise<OpenSecureWindowResponse>
openAuthSession(options: OpenAuthSessionOptions) => Promise<OpenAuthSessionResult>Opens a system auth session for generic OAuth/OIDC or enterprise SSO.
Use this when you build the authorize URL yourself (or your IdP SDK returns one) and only need the plugin to run the secure browser flow and return the redirect callback URL. Exchange the authorization code or tokens on your backend or with your own client logic.
iOS/Android: system browser session (ASWebAuthenticationSession / Chrome Custom Tabs).
Web: popup window plus BroadcastChannel (not a native browser session).
On user cancel or dismiss, the Promise rejects with code === 'USER_CANCELLED'.
| Param | Type | Description |
|---|---|---|
options |
OpenAuthSessionOptions |
- auth session options |
Returns: Promise<OpenAuthSessionResult>
| Prop | Type | Description |
|---|---|---|
oauth2 |
Record<string, OAuth2ProviderConfig> |
OAuth2 provider configurations. Supports multiple providers by using a Record with provider IDs as keys. |
telegram |
{ botId: string; redirectUrl?: string; origin?: string; requestAccess?: 'read' | 'write'; languageCode?: string; } |
Telegram Login Widget configuration. Uses Telegram's OAuth widget (oauth.telegram.org), not standard OAuth2. |
linkedin |
LinkedInProviderConfig |
LinkedIn configuration. Convenience wrapper that maps to the OAuth2 provider using LinkedIn defaults. |
tiktok |
TikTokProviderConfig |
TikTok Login Kit configuration. Convenience wrapper that maps to the OAuth2 provider using TikTok defaults (client_key). |
twitter |
{ clientId: string; redirectUrl: string; defaultScopes?: string[]; forceLogin?: boolean; audience?: string; } |
|
facebook |
{ appId: string; clientToken?: string; locale?: string; } |
|
google |
{ iOSClientId?: string; iOSServerClientId?: string; webClientId?: string; mode?: 'online' | 'offline'; hostedDomain?: string; redirectUrl?: string; skipAuthOnlyAuthorizationAfterSignIn?: boolean; } |
|
apple |
{ clientId?: string; redirectUrl?: string; useProperTokenExchange?: boolean; useBroadcastChannel?: boolean; } |
Configuration for a single OAuth2 provider instance
| Prop | Type | Description | Default |
|---|---|---|---|
appId |
string |
The OAuth 2.0 client identifier (App ID / Client ID). Note: this configuration object is only used by the plugin's built-in oauth2 provider (i.e. SocialLogin.initialize({ oauth2: { ... } })). It does not affect Google/Apple/Facebook/Twitter. |
|
clientId |
string |
Alias for appId to match common OAuth/OIDC naming (clientId). If both are provided, appId takes precedence. |
|
issuerUrl |
string |
OpenID Connect issuer URL (enables discovery via /.well-known/openid-configuration). When set, you may omit explicit endpoints like authorizationBaseUrl and accessTokenEndpoint. Notes: - Explicit endpoints (authorization/token/logout) take precedence over discovered values. - Discovery is supported for oauth2 on Web, iOS, and Android. |
|
authorizationBaseUrl |
string |
The base URL of the authorization endpoint | |
authorizationEndpoint |
string |
Alias for authorizationBaseUrl (to match common OAuth/OIDC naming). |
|
clientSecret |
string |
OAuth 2.0 client secret for token requests (e.g., when exchanging the code). When provided, this value is sent using clientSecretParamName (default client_secret). |
|
clientIdParamName |
string |
Override the client identifier parameter name used for authorization and token requests. Some providers (e.g. TikTok) expect client_key instead of the default client_id. |
'client_id' |
clientSecretParamName |
string |
Override the client secret parameter name used for token requests. Useful for providers that expect a different parameter name. | 'client_secret' |
accessTokenEndpoint |
string |
The URL to exchange the authorization code for tokens Required for authorization code flow | |
tokenEndpoint |
string |
Alias for accessTokenEndpoint (to match common OAuth/OIDC naming). |
|
redirectUrl |
string |
Redirect URL that receives the OAuth callback | |
resourceUrl |
string |
Optional URL to fetch user profile/resource data after authentication The access token will be sent as Bearer token in the Authorization header | |
responseType |
'code' | 'token' |
The OAuth response type - 'code': Authorization Code flow (recommended, requires accessTokenEndpoint) - 'token': Implicit flow (less secure, tokens returned directly) | 'code' |
pkceEnabled |
boolean |
Enable PKCE (Proof Key for Code Exchange) Strongly recommended for public clients (mobile/web apps) | true |
scope |
string | string[] |
Default scopes to request during authorization | |
scopes |
string[] |
Alias for scope using common naming (scopes). If both are provided, scope takes precedence. |
|
additionalParameters |
Record<string, string> |
Additional parameters to include in the authorization request | |
loginHint |
string |
Convenience option for OIDC login_hint. Equivalent to passing additionalParameters.login_hint. |
|
prompt |
string |
Convenience option for OAuth/OIDC prompt. Equivalent to passing additionalParameters.prompt. |
|
additionalTokenParameters |
Record<string, string> |
Additional parameters to include in token requests (code exchange / refresh). Useful for providers that require non-standard parameters. | |
additionalResourceHeaders |
Record<string, string> |
Additional headers to include when fetching the resource URL | |
logoutUrl |
string |
Custom logout URL for ending the session | |
endSessionEndpoint |
string |
Alias for logoutUrl to match OIDC naming (endSessionEndpoint). |
|
postLogoutRedirectUrl |
string |
OIDC post logout redirect URL (sent as post_logout_redirect_uri when building the end-session URL). |
|
additionalLogoutParameters |
Record<string, string> |
Additional parameters to include in logout / end-session URL. | |
iosPrefersEphemeralWebBrowserSession |
boolean |
iOS-only: Whether to prefer an ephemeral browser session for ASWebAuthenticationSession. Defaults to true to match existing behavior in this plugin. | |
iosPrefersEphemeralSession |
boolean |
Alias for iosPrefersEphemeralWebBrowserSession (to match Capawesome OAuth naming). |
|
androidUseCustomTabs |
boolean |
Android-only: Use Chrome Custom Tabs (system browser) instead of an embedded WebView for the authorization request. Custom Tabs follow RFC 8252 (OAuth 2.0 for Native Apps) and fix issues with brokered IdPs (Microsoft Entra Conditional Access / Authenticator, passkeys/WebAuthn, Google disallowed_useragent, SSO cookie sharing, password managers). Requires a custom-scheme or App Link redirectUrl with a matching intent filter in your app's AndroidManifest.xml (same setup as openSecureWindow() / Apple on Android). Defaults to false to preserve the historical WebView flow. |
false |
logsEnabled |
boolean |
Enable debug logging | false |
LinkedIn provider configuration (convenience wrapper around the generic OAuth2 provider).
Uses the OAuth2 engine with LinkedIn defaults:
- Authorization URL: https://www.linkedin.com/oauth/v2/authorization
- Token URL: https://www.linkedin.com/oauth/v2/accessToken
- Resource URL: https://api.linkedin.com/v2/userinfo
- Default scopes:
openid profile email
| Prop | Type | Description |
|---|---|---|
clientId |
string |
LinkedIn Client ID from the LinkedIn Developer Portal. |
redirectUrl |
string |
Redirect URL that receives the OAuth callback. Must match a redirect URL configured in the LinkedIn Developer Portal. |
clientSecret |
string |
LinkedIn Client Secret. Prefer exchanging the authorization code on a backend when possible. Needed for confidential clients that do not use PKCE-only token exchange. |
TikTok Login Kit configuration (convenience wrapper around the generic OAuth2 provider).
Uses TikTok OAuth 2.0 endpoints and client_key instead of client_id.
| Prop | Type | Description | Default |
|---|---|---|---|
clientKey |
string |
TikTok client key (also known as app key). | |
redirectUrl |
string |
Redirect URL registered in your TikTok developer app. | |
clientSecret |
string |
TikTok client secret. Optional. When set, the plugin includes it on token and refresh requests. On web this value is stored with the OAuth2 config. Login always exchanges the authorization code in the plugin; the raw code is not returned to the app. | |
scopes |
string[] |
Scopes to request during login. Arrays are sent as a comma-separated string (TikTok Login Kit). | ['user.info.basic'] |
scope |
string | string[] |
Alias for scopes. |
|
pkceEnabled |
boolean |
Toggle PKCE usage during the authorization code flow. | true |
logsEnabled |
boolean |
Enable verbose debug logging for the TikTok OAuth2 flow. | false |
| Prop | Type | Description | Since |
|---|---|---|---|
accessToken |
AccessToken | null |
||
isLimitedLogin |
boolean |
Whether Facebook Limited Login was used for this session. When true, accessToken is not valid for Graph API calls (Facebook error 190). Validate idToken on your backend instead, or call facebook#requestTracking and log in again after ATT is granted. |
8.4.0 |
idToken |
string | null |
OpenID Connect ID token (JWT) from Meta Limited Login (iOS native, when available). Not equivalent to Google/Apple email_verified: Meta's OIDC token may include an email claim (when the email permission is granted) but does not publish an email_verified claim like Google or Apple. Meta documents the value as the user's primary account email, not as an OIDC-verified email assertion. On Android and Web this is usually null (Graph API access token flow instead). Validate signature, iss (https://www.facebook.com or https://limited.facebook.com), aud, exp, and nonce on your backend. Do not infer email_verified: true from the presence of email alone when linking accounts across providers. |
|
profile |
{ userID: string; email: string | null; friendIDs: string[]; birthday: string | null; ageRange: { min?: number; max?: number; } | null; gender: string | null; location: { id: string; name: string; } | null; hometown: { id: string; name: string; } | null; profileURL: string | null; name: string | null; imageURL: string | null; } |
| Prop | Type |
|---|---|
applicationId |
string |
declinedPermissions |
string[] |
expires |
string |
isExpired |
boolean |
lastRefresh |
string |
permissions |
string[] |
token |
string |
tokenType |
string |
refreshToken |
string |
userId |
string |
| Prop | Type | Description |
|---|---|---|
accessToken |
AccessToken | null |
OAuth access token for Google APIs. May be null on Android when AuthorizationClient does not return an access token, or when skipAuthOnlyAuthorizationAfterSignIn is enabled during initialize (opt-in). Use idToken for user authentication; request additional Google API scopes when an access token is required. |
idToken |
string | null |
OpenID Connect ID token (JWT). Includes an email_verified claim when the email scope is granted. Use SocialLogin.decodeIdToken({ idToken }) to read claims on the client, but always verify the token signature, iss, aud, and exp on your backend before trusting email_verified for account linking. |
profile |
{ email: string | null; familyName: string | null; givenName: string | null; id: string | null; name: string | null; imageUrl: string | null; } |
|
responseType |
'online' |
| Prop | Type |
|---|---|
serverAuthCode |
string |
responseType |
'offline' |
| Prop | Type | Description |
|---|---|---|
accessToken |
AccessToken | null |
Access token from Apple |
idToken |
string | null |
Identity token (JWT) from Apple. Includes standard OIDC claims such as sub, email (when granted), and email_verified (boolean). Apple sets email_verified to true when it attests the user controls the email (including Hide My Email relay addresses). Use SocialLogin.decodeIdToken({ idToken }) to read claims on the client, but verify the token signature, iss, aud, and exp on your backend before trusting email_verified for account linking. |
profile |
{ user: string; email: string | null; givenName: string | null; familyName: string | null; } |
User profile information |
authorizationCode |
string |
Authorization code for proper token exchange (when useProperTokenExchange is enabled) |
| Prop | Type |
|---|---|
accessToken |
AccessToken | null |
refreshToken |
string | null |
scope |
string[] |
tokenType |
'bearer' |
expiresIn |
number | null |
profile |
TwitterProfile |
| Prop | Type |
|---|---|
id |
string |
username |
string |
name |
string | null |
profileImageUrl |
string | null |
verified |
boolean |
email |
string | null |
| Prop | Type | Description |
|---|---|---|
profile |
TelegramProfile |
|
authDate |
number |
Unix timestamp (seconds) when the user authorized the login. |
hash |
string |
Telegram-provided hash for server-side verification. |
requestAccess |
'read' | 'write' |
Requested access level that was used for this login. |
| Prop | Type |
|---|---|
id |
string |
firstName |
string |
lastName |
string | null |
username |
string | null |
photoUrl |
string | null |
| Prop | Type | Description |
|---|---|---|
providerId |
string |
The provider ID that was used for this login |
accessToken |
AccessToken | null |
The access token received from the OAuth provider |
idToken |
string | null |
The ID token (JWT) if provided by the OAuth server (e.g., OpenID Connect) |
refreshToken |
string | null |
The refresh token if provided (requires appropriate scope like offline_access) |
resourceData |
Record<string, unknown> | null |
Resource data fetched from resourceUrl if configured Contains the raw JSON response from the resource endpoint |
scope |
string[] |
The scopes that were granted |
tokenType |
string |
Token type (usually 'bearer') |
expiresIn |
number | null |
Token expiration time in seconds |
| Prop | Type | Description | Default |
|---|---|---|---|
permissions |
string[] |
Permissions | |
limitedLogin |
boolean |
Is Limited Login | false |
nonce |
string |
Nonce |
| Prop | Type | Description | Default | Since |
|---|---|---|---|---|
scopes |
string[] |
Specifies the scopes required for accessing Google APIs The default is defined in the configuration. | ||
nonce |
string |
Nonce. On iOS, a login with a nonce always shows the Google sign-in instead of restoring the previous sign-in: a restored ID token was minted without this nonce, so a backend that verifies it (for example Supabase signInWithIdToken) would reject the token. |
||
forceRefreshToken |
boolean |
Force refresh token (only for Android) | false |
|
forcePrompt |
boolean |
Force account selection prompt (iOS) | false |
|
style |
'bottom' | 'standard' |
Style | 'standard' |
|
filterByAuthorizedAccounts |
boolean |
Filter by authorized accounts (Android only) | false |
|
autoSelectEnabled |
boolean |
Auto select enabled (Android only) | false |
|
prompt |
'none' | 'consent' | 'select_account' | 'consent select_account' | 'select_account consent' |
Prompt parameter for Google OAuth (Web only) | 7.12.0 |
| Prop | Type | Description | Default |
|---|---|---|---|
scopes |
string[] |
Scopes | |
nonce |
string |
Nonce | |
state |
string |
State | |
useBroadcastChannel |
boolean |
Use Broadcast Channel for authentication flow | false |
| Prop | Type | Description |
|---|---|---|
scopes |
string[] |
Additional scopes to request during login. If omitted the plugin falls back to the default scopes configured during initialization. |
state |
string |
Provide a custom OAuth state value. When not provided the plugin generates a cryptographically random value. |
codeVerifier |
string |
Provide a pre-computed PKCE code verifier (mostly used for testing). When omitted the plugin generates a secure verifier automatically. |
redirectUrl |
string |
Override the redirect URI for a single login call. Useful when the same app supports multiple callback URLs per platform. |
forceLogin |
boolean |
Force the consent screen on every attempt, maps to force_login=true. |
| Prop | Type | Description | Default |
|---|---|---|---|
redirectUrl |
string |
Override the redirect URL for this login attempt. Defaults to the redirect configured during initialize(). Required on iOS/Android when initialize() did not set redirectUrl. |
|
state |
string |
Optional state parameter for CSRF protection. If omitted, a secure random value is generated automatically. | |
requestAccess |
'read' | 'write' |
Override requested access level for this login. Defaults to the value configured during initialize(). | 'write' |
| Prop | Type | Description | Default |
|---|---|---|---|
providerId |
string |
The provider ID as configured in initialize() This is required to identify which OAuth2 provider to use | |
scope |
string | string[] |
Override the scopes for this login request If not provided, uses the scopes from initialization | |
scopes |
string[] |
Alias for scope using common naming (scopes). If both are provided, scope takes precedence. |
|
state |
string |
Custom state parameter for CSRF protection If not provided, a random value is generated | |
codeVerifier |
string |
Override PKCE code verifier (for testing purposes) If not provided, a secure random verifier is generated | |
redirectUrl |
string |
Override redirect URL for this login request | |
additionalParameters |
Record<string, string> |
Additional parameters to add to the authorization URL | |
loginHint |
string |
Convenience option for OIDC login_hint. Equivalent to passing additionalParameters.login_hint. |
|
prompt |
string |
Convenience option for OAuth/OIDC prompt. Equivalent to passing additionalParameters.prompt. |
|
flow |
'popup' | 'redirect' |
Web-only (oauth2 provider only): Use a full-page redirect instead of a popup window. When using redirect, the promise returned by login() will not resolve because the page navigates away. After the redirect lands back in your app, call SocialLogin.handleRedirectCallback() on that page to parse the result. |
'popup' |
| Prop | Type | Description |
|---|---|---|
scopes |
string[] |
Optional scopes to override the initialization scopes. |
scope |
string | string[] |
Alias for scopes. |
state |
string |
Custom state parameter for CSRF protection. |
codeVerifier |
string |
Custom PKCE code verifier (mostly for testing). |
redirectUrl |
string |
Override redirect URL for this login request. |
| Prop | Type | Description |
|---|---|---|
provider |
'apple' | 'google' | 'facebook' | 'twitter' | 'linkedin' | 'tiktok' | 'oauth2' | 'telegram' |
Provider |
providerId |
string |
Provider ID for OAuth2 providers (required when provider is 'oauth2') |
| Prop | Type | Description |
|---|---|---|
jwt |
string |
Jwt |
accessToken |
string |
Access Token |
| Prop | Type | Description |
|---|---|---|
provider |
'apple' | 'google' | 'facebook' | 'twitter' | 'linkedin' | 'tiktok' | 'oauth2' |
Provider |
providerId |
string |
Provider ID for OAuth2 providers (required when provider is 'oauth2') |
| Prop | Type | Description |
|---|---|---|
profile |
{ [key: string]: any; id: string | null; name: string | null; email: string | null; first_name: string | null; last_name: string | null; picture?: { data: { height: number | null; is_silhouette: boolean | null; url: string | null; width: number | null; }; } | null; } |
Facebook profile data |
| Prop | Type | Description |
|---|---|---|
status |
'authorized' | 'denied' | 'notDetermined' | 'restricted' |
App tracking authorization status |
Response from google#createRestoreCredential.
Send responseJson to your server to complete restore key registration (same as passkey creation).
| Prop | Type | Description |
|---|---|---|
responseJson |
string |
Public key credential registration response JSON from Credential Manager. |
Response from google#getRestoreCredential.
Send responseJson to your server to sign the user in (same server path as passkey authentication).
| Prop | Type | Description |
|---|---|---|
responseJson |
string |
Restore credential authentication response JSON from Credential Manager. |
Response from google#clearRestoreCredential.
| Prop | Type | Description |
|---|---|---|
cleared |
boolean |
Whether the restore credential clear request completed successfully. |
| Prop | Type | Description | Default |
|---|---|---|---|
fields |
string[] |
Fields to retrieve from Facebook profile. | ['id', 'name', 'email', 'picture'] |
Options for providerSpecificCall with google#createRestoreCredential.
Android-only. Creates a Restore Credential (restore key) via Credential Manager after the user signs in. Your backend must supply WebAuthn PublicKeyCredentialCreationOptionsJSON (the same FIDO2/passkey registration flow used for passkeys).
| Prop | Type | Description | Default |
|---|---|---|---|
requestJson |
string |
Credential creation options from your server in WebAuthn PublicKeyCredentialCreationOptionsJSON format. | |
isCloudBackupEnabled |
boolean |
When true (default), the restore key is backed up to the cloud when the user has backup and end-to-end encryption (e.g. screen lock) enabled. If cloud backup creation fails with E2eeUnavailableException on Android, the plugin automatically retries with local-only storage. |
true |
Options for providerSpecificCall with google#getRestoreCredential.
Android-only. Retrieves a Restore Credential silently (e.g. on first launch on a new device or from
BackupAgent onRestoreFinished). Your backend must supply WebAuthn authentication request JSON.
| Prop | Type | Description |
|---|---|---|
requestJson |
string |
Credential request options from your server (WebAuthn authentication request JSON). |
| Prop | Type | Description |
|---|---|---|
redirectedUri |
string |
The result of the openSecureWindow call |
| Prop | Type | Description |
|---|---|---|
authEndpoint |
string |
The endpoint to open |
redirectUri |
string |
The redirect URI to use for the openSecureWindow call. This will be checked to make sure it matches the redirect URI after the window finishes the redirection. |
broadcastChannelName |
string |
The name of the broadcast channel to listen to, relevant only for web |
| Prop | Type | Description |
|---|---|---|
callbackURL |
string |
Full redirect URI returned by the identity provider, including query or fragment (e.g. myapp://auth/callback?code=...&state=...). |
| Prop | Type | Description | Default |
|---|---|---|---|
url |
string |
Authorization or login URL to open in the system browser session (OAuth/OIDC authorize endpoint, SSO login page, etc.). | |
callbackURLScheme |
string |
Custom URL scheme that receives the redirect (without ://). Must match the scheme in your registered redirect URI and native URL handler (iOS/Android). On Web, the plugin also accepts HTTPS redirect URLs when redirect_uri is present in url, or messages prefixed with ${callbackURLScheme}:// on the BroadcastChannel. |
|
prefersEphemeralSession |
boolean |
iOS-only: prefer an ephemeral ASWebAuthenticationSession (no shared cookies with Safari). Defaults to false so SSO cookies in the system browser can be reused. |
|
broadcastChannelName |
string |
Web-only: BroadcastChannel name used by the redirect page to post the callback URL back to the app. |
'capgo-auth-session' |
Construct a type with a set of properties K of type T
{
[P in K]: T;
}
{ facebook: FacebookLoginResponse; google: GoogleLoginResponse; apple: AppleProviderResponse; twitter: TwitterLoginResponse; telegram: TelegramLoginResponse; linkedin: LinkedInLoginResponse; tiktok: TikTokLoginResponse; oauth2: OAuth2LoginResponse; }
GoogleLoginResponseOnline | GoogleLoginResponseOffline
LinkedIn login response (returned when using the LinkedIn convenience API).
TikTok login response (same shape as generic OAuth2).
{ provider: 'facebook'; options: FacebookLoginOptions; } | { provider: 'google'; options: GoogleLoginOptions; } | { provider: 'apple'; options: AppleProviderOptions; } | { provider: 'twitter'; options: TwitterLoginOptions; } | { provider: 'telegram'; options: TelegramLoginOptions; } | { provider: 'linkedin'; options: LinkedInLoginOptions; } | { provider: 'tiktok'; options: TikTokLoginOptions; } | { provider: 'oauth2'; options: OAuth2LoginOptions; }
LinkedIn login options (maps to the OAuth2 provider internally).
providerId is set to linkedin automatically.
Omit<OAuth2LoginOptions, 'providerId'>
Construct a type with the properties of T except for those in type K.
From T, pick a set of properties whose keys are in the union K
{
[P in K]: T[P];
}
Exclude from T those types that are assignable to U
T extends U ? never : T
Extract from T those types that are assignable to U
T extends U ? T : never
Options for refreshToken().
providerId is required for generic oauth2 and ignored for LinkedIn and TikTok.
{ provider: 'oauth2'; providerId: string; refreshToken?: string; additionalParameters?: Record<string, string>; } | { provider: 'linkedin'; providerId?: string; refreshToken?: string; additionalParameters?: Record<string, string>; } | { provider: 'tiktok'; providerId?: string; refreshToken?: string; additionalParameters?: Record<string, string>; }
{ provider: 'facebook'; result: FacebookLoginResponse; } | { provider: 'google'; result: GoogleLoginResponse; } | { provider: 'apple'; result: AppleProviderResponse; } | { provider: 'twitter'; result: TwitterLoginResponse; } | { provider: 'telegram'; result: TelegramLoginResponse; } | { provider: 'linkedin'; result: LinkedInLoginResponse; } | { provider: 'tiktok'; result: TikTokLoginResponse; } | { provider: 'oauth2'; result: OAuth2LoginResponse; }
{ 'facebook#getProfile': FacebookGetProfileResponse; 'facebook#requestTracking': FacebookRequestTrackingResponse; 'google#createRestoreCredential': GoogleCreateRestoreCredentialResponse; 'google#getRestoreCredential': GoogleGetRestoreCredentialResponse; 'google#clearRestoreCredential': GoogleClearRestoreCredentialResponse; }
'facebook#getProfile' | 'facebook#requestTracking' | 'google#createRestoreCredential' | 'google#getRestoreCredential' | 'google#clearRestoreCredential'
{ 'facebook#getProfile': FacebookGetProfileOptions; 'facebook#requestTracking': FacebookRequestTrackingOptions; 'google#createRestoreCredential': GoogleCreateRestoreCredentialOptions; 'google#getRestoreCredential': GoogleGetRestoreCredentialOptions; 'google#clearRestoreCredential': GoogleClearRestoreCredentialOptions; }
Record<string, never>
Options for google#clearRestoreCredential (no fields).
Record<string, never>
If you use Google, Facebook, or Apple login, you must declare the data collected by their SDKs in your app's PrivacyInfo.xcprivacy file (not in the plugin).
Add this file in your app at: ios/App/PrivacyInfo.xcprivacy
{
"NSPrivacyCollectedDataTypes": [
{ "NSPrivacyCollectedDataType": "EmailAddress", "NSPrivacyCollectedDataTypeLinked": true, "NSPrivacyCollectedDataTypeTracking": false },
{ "NSPrivacyCollectedDataType": "Name", "NSPrivacyCollectedDataTypeLinked": true, "NSPrivacyCollectedDataTypeTracking": false },
{ "NSPrivacyCollectedDataType": "UserID", "NSPrivacyCollectedDataTypeLinked": true, "NSPrivacyCollectedDataTypeTracking": false }
]
}{
"NSPrivacyCollectedDataTypes": [
{ "NSPrivacyCollectedDataType": "EmailAddress", "NSPrivacyCollectedDataTypeLinked": true, "NSPrivacyCollectedDataTypeTracking": false },
{ "NSPrivacyCollectedDataType": "Name", "NSPrivacyCollectedDataTypeLinked": true, "NSPrivacyCollectedDataTypeTracking": false },
{ "NSPrivacyCollectedDataType": "UserID", "NSPrivacyCollectedDataTypeLinked": true, "NSPrivacyCollectedDataTypeTracking": false },
{ "NSPrivacyCollectedDataType": "FriendsList", "NSPrivacyCollectedDataTypeLinked": true, "NSPrivacyCollectedDataTypeTracking": false }
]
}{
"NSPrivacyCollectedDataTypes": [
{ "NSPrivacyCollectedDataType": "EmailAddress", "NSPrivacyCollectedDataTypeLinked": true, "NSPrivacyCollectedDataTypeTracking": false },
{ "NSPrivacyCollectedDataType": "Name", "NSPrivacyCollectedDataTypeLinked": true, "NSPrivacyCollectedDataTypeTracking": false }
]
}- Adjust the data types to match your app's usage and the SDK documentation.
- See Apple docs for all allowed keys and values.
Use AppDelegate handlers only when your app does not use the Capacitor 8.5 UIScene manifest. With UIScene, forward all contexts from SceneDelegate.scene(_:openURLContexts:) to SceneDelegateProxy.shared.scene(scene, openURLContexts:) and let the plugin observer call the SDK handlers (see Google iOS setup and the Facebook iOS section above).
This plugin listens for Capacitor's capacitorOpenURL notification and calls the Facebook and Google URL handlers for you when those SDKs are linked. It also listens for capacitorOpenUniversalLink and routes matching Facebook App Links into the Facebook SDK (Google still uses the open URL path). Custom native URL code is optional.
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
// Forward every URL so Capacitor posts capacitorOpenURL. This plugin's observer calls the Facebook and Google handlers.
return ApplicationDelegateProxy.shared.application(app, open: url, options: options)
} func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
// Forward every context. The plugin observer calls the Facebook and Google
// URL handlers once per URL, so do not call them here as well.
SceneDelegateProxy.shared.scene(scene, openURLContexts: URLContexts)
}This plugin implementation of google is based on CapacitorGoogleAuth with a lot of rework, the current maintainer is unreachable, we are thankful for his work and are now going forward on our own! Thanks to reslear for helping to transfer users to this plugin from the old one and all the work.
