@capgo/capacitor-social-login

July 7, 2026 · View on GitHub

Capgo - Instant updates for Capacitor

➡️ Get Instant updates for your App with Capgo

Missing a feature? We’ll build the plugin for you 💪

Fork Information

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.

About

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)
  • 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.

Ionic Auth Connect compatibility

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.

Documentation

Best experience to read the doc here:

https://capgo.app/docs/plugins/social-login/getting-started/

Compatibility

Plugin versionCapacitor compatibilityMaintained
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.

Install

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-plugins

Then 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 sync

Dynamic Provider Dependencies

You can configure which providers to include to reduce app size. This is especially useful if you only need specific providers.

Configuration

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, no external deps
        twitter: false   // false = disabled (not bundled)
      },
      logLevel: 1 // Warnings and errors only
    }
  }
};

export default config;

Provider Configuration

  • true (default): Provider is enabled - dependencies are bundled in final APK/IPA
  • false: Provider is disabled - dependencies are not bundled in final APK/IPA

Notes

  • Changes require running npx cap sync to 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 false means the dependency won't be bundled, but the plugin code still compiles against it. Ensure the consuming app includes the dependency if needed.
  • Apple Sign-In on Android uses OAuth flow without external SDK dependencies
  • Twitter uses standard OAuth 2.0 flow without external SDK dependencies

Example: Reduce App Size

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)
    }
  }
}

Apple

How to get the credentials How to setup redirect url

Android configuration

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'],
  },
});

iOS configuration

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'],
  },
});

Facebook

Docs: How to setup facebook login

📘 Complete Facebook Business Login Guide - Learn how to access Instagram, Pages, and business features

Facebook Business Login

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.

Supported Business Permissions:

  • instagram_basic - Access to Instagram Basic Display API
  • instagram_manage_insights - Access to Instagram Insights
  • pages_show_list - List of Pages the person manages
  • pages_read_engagement - Read engagement data from Pages
  • pages_manage_posts - Manage posts on Pages
  • business_management - Manage business assets
  • And many more - see Facebook Permissions Reference

Configuration Requirements:

  1. Your Facebook app must be configured as a Business app in the Facebook Developer Console
  2. Business permissions may require Facebook's App Review before production use
  3. 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

Android configuration

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'],
  },
});

iOS configuration

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 {
        // Called when the app was launched with a url. Feel free to add additional processing here,
        // but if you want the App API to support tracking app url opens, make sure to keep this call
        if (FBSDKCoreKit.ApplicationDelegate.shared.application(
            app,
            open: url,
            sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String,
            annotation: options[UIApplication.OpenURLOptionsKey.annotation]
        )) {
            return true;
        } else {
            return ApplicationDelegateProxy.shared.application(app, open: url, options: options)
        }
    }
}

Add the following in the ios/App/App/info.plist file inside of the outermost <dict>:


<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

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'],
  },
});

Google

How to get the credentials

Complete Configuration Example

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 platforms
  • iOSClientId: Required for iOS platform
  • iOSServerClientId: Required when using mode: 'offline' on iOS or when you need to verify the token on the server (should be the same value as webClientId)
  • mode: 'offline': Returns only serverAuthCode for backend authentication, no user profile data, and refresh() is not available in-app. Exchange serverAuthCode on your backend and refresh there.
  • mode: 'online': Returns user profile data and access tokens (default)

Android configuration

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: {
    scopes: ['email', 'profile'],
  },
});

Android troubleshooting (Credential Manager, SHA-1, and Firebase)

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.

Required Google Cloud setup (all in the same project)

You need two kinds of OAuth 2.0 client IDs:

Client typeUsed forWhere it goes
Web applicationServer / ID token audiencewebClientId in SocialLogin.initialize()
Android (one per signing key)Proves your APK is allowed to call GoogleGoogle 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 integrityApp 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.

Error [28444] Developer console is not set up correctly

This almost always means Google rejected the combination of installed APK signing certificate, package name, and **webClientId`. Work through this checklist:

  1. Confirm webClientId is the Web application client ID (ends with .apps.googleusercontent.com).
  2. Run the app, reproduce the failure, and read Logcat (GoogleProvider) for signingSha1= and package=.
  3. In Google Cloud Console → Credentials, open your Android OAuth client and verify that exact package name and SHA-1 are listed.
  4. If testing a release build, register the SHA-1 from that build — not only the debug keystore.
  5. If the app is distributed via Play Store, also register the Play App Signing SHA-1.
  6. Ensure Web and Android clients live in the same Google Cloud project.
  7. If consent screen is in Testing, confirm the Google account is a test user.
  8. 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.

Extract SHA-1 from the build you install

Debug / local builds:

cd android && ./gradlew signingReport

Signed release APK:

keytool -printcert -jarfile android/app/release/app-release.apk

Then 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.apk
Reading the login result (Firebase and backends)

Tokens are nested under result:

const login = await SocialLogin.login({ provider: 'google' });
const idToken = login.result?.idToken; // not login.idToken

For Firebase Auth, create credentials with that idToken and use the Web Client ID as webClientId in initialize.

iOS configuration

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'],
  },
});

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.

Web

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.

OAuth2 (Generic)

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.

Multi-Provider Configuration

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',
      },
    },
  },
});

Auth Connect Presets (Auth0, Azure AD, Cognito, Okta, OneLogin)

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 oauth2 entry 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, or logoutUrl in the preset.

Login with a Specific Provider

// 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);

Check Login Status

const status = await SocialLogin.isLoggedIn({
  provider: 'oauth2',
  providerId: 'github',  // Required for OAuth2
});
console.log('Is logged in:', status.isLoggedIn);

Logout

await SocialLogin.logout({
  provider: 'oauth2',
  providerId: 'github',  // Required for OAuth2
});

Refresh Token

await SocialLogin.refresh({
  provider: 'oauth2',
  options: {
    providerId: 'github',  // Required for OAuth2
  },
});

OAuth2 Configuration Options

OptionTypeRequiredDescription
appIdstringYesOAuth2 Client ID
issuerUrlstringNo*OpenID Connect issuer URL for discovery (*Use this or an authorization endpoint)
authorizationBaseUrl / authorizationEndpointstringNo*Authorization endpoint URL aliases for the same setting (*Use one alias or issuerUrl)
accessTokenEndpoint / tokenEndpointstringNo*Token endpoint URL aliases for the same setting (*Required for code flow without issuerUrl)
redirectUrlstringYesCallback URL for OAuth redirect
responseType'code' | 'token'NoOAuth flow type (default: 'code')
pkceEnabledbooleanNoEnable PKCE (default: true)
scopestringNoDefault scopes to request
resourceUrlstringNoURL to fetch user profile after auth
additionalParametersRecord<string, string>NoExtra params for authorization URL
additionalResourceHeadersRecord<string, string>NoExtra headers for resource request
logoutUrlstringNoURL to open on logout
logsEnabledbooleanNoEnable debug logging (default: false)

Platform-Specific Notes

iOS: Uses ASWebAuthenticationSession for secure authentication.

Android: Uses a WebView-based authentication flow.

Web: Opens a popup window for OAuth flow.

Security Recommendations

  1. Always use PKCE (pkceEnabled: true) for public clients
  2. Use authorization code flow (responseType: 'code') instead of implicit flow
  3. Store tokens securely using @capgo/capacitor-persistent-account
  4. Use HTTPS for all endpoints and redirect URLs in production

Troubleshooting

Invalid Privacy Manifest (ITMS-91056)

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.xcprivacy is valid JSON, with only Apple-documented keys/values.
  • Do not include a privacy manifest in the plugin, only in your app.

Google Play Console AD_ID Permission Error

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.

Google Sign-In [28444] Developer console is not set up correctly (Android)

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.

Problem: When users try to sign in with Google accounts supervised by Family Link, login fails with:

NoCredentialException: No credentials available

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 true)
    scopes: ['profile', 'email']
  }
});

Key Points:

  • Set filterByAuthorizedAccounts to false to ensure Family Link accounts are visible (default is true)
  • 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 filterByAuthorizedAccounts if 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.

Where to store access tokens?

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.

API

initialize(...)

initialize(options: InitializeOptions) => Promise<void>

Initialize the plugin

ParamType
optionsInitializeOptions

login(...)

login<T extends "apple" | "google" | "facebook" | "twitter" | "oauth2">(options: Extract<LoginOptions, { provider: T; }>) => Promise<{ provider: T; result: ProviderResponseMap[T]; }>

Login with the selected provider

ParamType
optionsExtract<{ 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: 'oauth2'; options: OAuth2LoginOptions; }, { provider: T; }>

Returns: Promise<{ provider: T; result: ProviderResponseMap[T]; }>


logout(...)

logout(options: { provider: 'apple' | 'google' | 'facebook' | 'twitter' | 'oauth2'; providerId?: string; }) => Promise<void>

Logout

ParamType
options{ provider: 'apple' | 'google' | 'facebook' | 'twitter' | 'oauth2'; providerId?: string; }

isLoggedIn(...)

isLoggedIn(options: isLoggedInOptions) => Promise<{ isLoggedIn: boolean; }>

IsLoggedIn

ParamType
optionsisLoggedInOptions

Returns: Promise<{ isLoggedIn: boolean; }>


getAuthorizationCode(...)

getAuthorizationCode(options: AuthorizationCodeOptions) => Promise<AuthorizationCode>

Get the current authorization code

ParamType
optionsAuthorizationCodeOptions

Returns: Promise<AuthorizationCode>


refresh(...)

refresh(options: LoginOptions) => Promise<void>

Refresh the access token

ParamType
optionsLoginOptions

refreshToken(...)

refreshToken(options: { provider: 'oauth2'; providerId: string; refreshToken?: string; additionalParameters?: Record<string, string>; }) => Promise<OAuth2LoginResponse>

OAuth2 refresh-token helper (feature parity with Capawesome OAuth).

Scope:

  • Only applies to the built-in oauth2 provider (not Google/Apple/Facebook/Twitter).
  • Requires a token endpoint (either accessTokenEndpoint/tokenEndpoint or issuerUrl discovery).

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).

ParamType
options{ provider: 'oauth2'; providerId: string; refreshToken?: string; additionalParameters?: Record<string, string>; }

Returns: Promise<OAuth2LoginResponse>


handleRedirectCallback()

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. oauth2 with flow: 'redirect') where the page navigates away.

Returns: Promise<LoginResult | null>


decodeIdToken(...)

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 idToken and token to match common naming (Capawesome uses token).
  • 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). When true, Google attests the user controls that email. Verify the JWT on your backend before trusting it.
  • Apple — ID token includes email_verified (boolean). When true, Apple attests the user controls that email (including private relay). Verify the JWT on your backend.
  • Meta (Facebook) — Limited Login OIDC tokens may include email but do not include email_verified. The presence of email is not the same guarantee as email_verified: true from Google or Apple. Do not link accounts by email across providers using Meta claims alone; perform your own email verification if needed.
ParamType
options{ idToken?: string; token?: string; }

Returns: Promise<{ claims: Record<string, any>; }>


getAccessTokenExpirationDate(...)

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.

ParamType
options{ accessTokenExpirationDate: number; }

Returns: Promise<{ date: string; }>


isAccessTokenAvailable(...)

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.

ParamType
options{ accessToken: string | null; }

Returns: Promise<{ isAvailable: boolean; }>


isAccessTokenExpired(...)

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.

ParamType
options{ accessTokenExpirationDate: number; }

Returns: Promise<{ isExpired: boolean; }>


isRefreshTokenAvailable(...)

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.

ParamType
options{ refreshToken: string | null; }

Returns: Promise<{ isAvailable: boolean; }>


providerSpecificCall(...)

providerSpecificCall<T extends ProviderSpecificCall>(options: { call: T; options: ProviderSpecificCallOptionsMap[T]; }) => Promise<ProviderSpecificCallResponseMap[T]>

Execute provider-specific calls

ParamType
options{ call: T; options: ProviderSpecificCallOptionsMap[T]; }

Returns: Promise<ProviderSpecificCallResponseMap[T]>


getPluginVersion()

getPluginVersion() => Promise<{ version: string; }>

Get the native Capacitor plugin version

Returns: Promise<{ version: string; }>


openSecureWindow(...)

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:

&lt;html&gt;
&lt;head&gt;&lt;/head&gt;
&lt;body&gt;
&lt;script&gt;
  const searchParams = new URLSearchParams(location.search)
  if (searchParams.has("code")) {
    new BroadcastChannel("my-channel-name").postMessage(location.href);
    window.close();
  }
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

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:

&lt;key&gt;CFBundleURLTypes&lt;/key&gt;
&lt;array&gt;
   &lt;dict&gt;
      &lt;key&gt;CFBundleURLSchemes&lt;/key&gt;
      &lt;array&gt;
         &lt;string&gt;myapp&lt;/string&gt;
      &lt;/array&gt;
   &lt;/dict&gt;
&lt;/array&gt;

And in the AndroidManifest.xml file:

&lt;activity&gt;
   &lt;intent-filter&gt;
      &lt;action android:name="android.intent.action.VIEW" /&gt;
      &lt;category android:name="android.intent.category.DEFAULT" /&gt;
      &lt;category android:name="android.intent.category.BROWSABLE" /&gt;
      &lt;data android:host="oauth_callback" android:scheme="myapp" /&gt;
   &lt;/intent-filter&gt;
&lt;/activity&gt;
ParamTypeDescription
optionsOpenSecureWindowOptions- the options for the openSecureWindow call

Returns: Promise<OpenSecureWindowResponse>


Interfaces

InitializeOptions

PropTypeDescription
oauth2Record<string, OAuth2ProviderConfig>OAuth2 provider configurations. Supports multiple providers by using a Record with provider IDs as keys.
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; }
apple{ clientId?: string; redirectUrl?: string; useProperTokenExchange?: boolean; useBroadcastChannel?: boolean; }

OAuth2ProviderConfig

Configuration for a single OAuth2 provider instance

PropTypeDescriptionDefault
appIdstringThe 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.
clientIdstringAlias for appId to match common OAuth/OIDC naming (clientId). If both are provided, appId takes precedence.
issuerUrlstringOpenID 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.
authorizationBaseUrlstringThe base URL of the authorization endpoint
authorizationEndpointstringAlias for authorizationBaseUrl (to match common OAuth/OIDC naming).
clientSecretstringOAuth 2.0 client secret for token requests (e.g., when exchanging the code). This value is sent as client_secret in token/refresh requests when provided.
accessTokenEndpointstringThe URL to exchange the authorization code for tokens Required for authorization code flow
tokenEndpointstringAlias for accessTokenEndpoint (to match common OAuth/OIDC naming).
redirectUrlstringRedirect URL that receives the OAuth callback
resourceUrlstringOptional 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'
pkceEnabledbooleanEnable PKCE (Proof Key for Code Exchange) Strongly recommended for public clients (mobile/web apps)true
scopestring | string[]Default scopes to request during authorization
scopesstring[]Alias for scope using common naming (scopes). If both are provided, scope takes precedence.
additionalParametersRecord<string, string>Additional parameters to include in the authorization request
loginHintstringConvenience option for OIDC login_hint. Equivalent to passing additionalParameters.login_hint.
promptstringConvenience option for OAuth/OIDC prompt. Equivalent to passing additionalParameters.prompt.
additionalTokenParametersRecord<string, string>Additional parameters to include in token requests (code exchange / refresh). Useful for providers that require non-standard parameters.
additionalResourceHeadersRecord<string, string>Additional headers to include when fetching the resource URL
logoutUrlstringCustom logout URL for ending the session
endSessionEndpointstringAlias for logoutUrl to match OIDC naming (endSessionEndpoint).
postLogoutRedirectUrlstringOIDC post logout redirect URL (sent as post_logout_redirect_uri when building the end-session URL).
additionalLogoutParametersRecord<string, string>Additional parameters to include in logout / end-session URL.
iosPrefersEphemeralWebBrowserSessionbooleaniOS-only: Whether to prefer an ephemeral browser session for ASWebAuthenticationSession. Defaults to true to match existing behavior in this plugin.
iosPrefersEphemeralSessionbooleanAlias for iosPrefersEphemeralWebBrowserSession (to match Capawesome OAuth naming).
logsEnabledbooleanEnable debug loggingfalse

FacebookLoginResponse

PropTypeDescriptionSince
accessTokenAccessToken | null
isLimitedLoginbooleanWhether 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
idTokenstring | nullOpenID 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; }

AccessToken

PropType
applicationIdstring
declinedPermissionsstring[]
expiresstring
isExpiredboolean
lastRefreshstring
permissionsstring[]
tokenstring
tokenTypestring
refreshTokenstring
userIdstring

GoogleLoginResponseOnline

PropTypeDescription
accessTokenAccessToken | null
idTokenstring | nullOpenID 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'

GoogleLoginResponseOffline

PropType
serverAuthCodestring
responseType'offline'

AppleProviderResponse

PropTypeDescription
accessTokenAccessToken | nullAccess token from Apple
idTokenstring | nullIdentity 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
authorizationCodestringAuthorization code for proper token exchange (when useProperTokenExchange is enabled)

TwitterLoginResponse

PropType
accessTokenAccessToken | null
refreshTokenstring | null
scopestring[]
tokenType'bearer'
expiresInnumber | null
profileTwitterProfile

TwitterProfile

PropType
idstring
usernamestring
namestring | null
profileImageUrlstring | null
verifiedboolean
emailstring | null

OAuth2LoginResponse

PropTypeDescription
providerIdstringThe provider ID that was used for this login
accessTokenAccessToken | nullThe access token received from the OAuth provider
idTokenstring | nullThe ID token (JWT) if provided by the OAuth server (e.g., OpenID Connect)
refreshTokenstring | nullThe refresh token if provided (requires appropriate scope like offline_access)
resourceDataRecord<string, unknown> | nullResource data fetched from resourceUrl if configured Contains the raw JSON response from the resource endpoint
scopestring[]The scopes that were granted
tokenTypestringToken type (usually 'bearer')
expiresInnumber | nullToken expiration time in seconds

FacebookLoginOptions

PropTypeDescriptionDefault
permissionsstring[]Permissions
limitedLoginbooleanIs Limited Loginfalse
noncestringNonce

GoogleLoginOptions

PropTypeDescriptionDefaultSince
scopesstring[]Specifies the scopes required for accessing Google APIs The default is defined in the configuration.
noncestringNonce
forceRefreshTokenbooleanForce refresh token (only for Android)false
forcePromptbooleanForce account selection prompt (iOS)false
style'bottom' | 'standard'Style'standard'
filterByAuthorizedAccountsbooleanFilter by authorized accounts (Android only)true
autoSelectEnabledbooleanAuto 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

AppleProviderOptions

PropTypeDescriptionDefault
scopesstring[]Scopes
noncestringNonce
statestringState
useBroadcastChannelbooleanUse Broadcast Channel for authentication flowfalse

TwitterLoginOptions

PropTypeDescription
scopesstring[]Additional scopes to request during login. If omitted the plugin falls back to the default scopes configured during initialization.
statestringProvide a custom OAuth state value. When not provided the plugin generates a cryptographically random value.
codeVerifierstringProvide a pre-computed PKCE code verifier (mostly used for testing). When omitted the plugin generates a secure verifier automatically.
redirectUrlstringOverride the redirect URI for a single login call. Useful when the same app supports multiple callback URLs per platform.
forceLoginbooleanForce the consent screen on every attempt, maps to force_login=true.

OAuth2LoginOptions

PropTypeDescriptionDefault
providerIdstringThe provider ID as configured in initialize() This is required to identify which OAuth2 provider to use
scopestring | string[]Override the scopes for this login request If not provided, uses the scopes from initialization
scopesstring[]Alias for scope using common naming (scopes). If both are provided, scope takes precedence.
statestringCustom state parameter for CSRF protection If not provided, a random value is generated
codeVerifierstringOverride PKCE code verifier (for testing purposes) If not provided, a secure random verifier is generated
redirectUrlstringOverride redirect URL for this login request
additionalParametersRecord<string, string>Additional parameters to add to the authorization URL
loginHintstringConvenience option for OIDC login_hint. Equivalent to passing additionalParameters.login_hint.
promptstringConvenience 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'

isLoggedInOptions

PropTypeDescription
provider'apple' | 'google' | 'facebook' | 'twitter' | 'oauth2'Provider
providerIdstringProvider ID for OAuth2 providers (required when provider is 'oauth2')

AuthorizationCode

PropTypeDescription
jwtstringJwt
accessTokenstringAccess Token

AuthorizationCodeOptions

PropTypeDescription
provider'apple' | 'google' | 'facebook' | 'twitter' | 'oauth2'Provider
providerIdstringProvider ID for OAuth2 providers (required when provider is 'oauth2')

FacebookGetProfileResponse

PropTypeDescription
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

FacebookRequestTrackingResponse

PropTypeDescription
status'authorized' | 'denied' | 'notDetermined' | 'restricted'App tracking authorization status

FacebookGetProfileOptions

PropTypeDescription
fieldsstring[]Fields to retrieve from Facebook profile

OpenSecureWindowResponse

PropTypeDescription
redirectedUristringThe result of the openSecureWindow call

OpenSecureWindowOptions

PropTypeDescription
authEndpointstringThe endpoint to open
redirectUristringThe 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.
broadcastChannelNamestringThe name of the broadcast channel to listen to, relevant only for web

Type Aliases

Record

Construct a type with a set of properties K of type T

{ [P in K]: T; }

ProviderResponseMap

{ facebook: FacebookLoginResponse; google: GoogleLoginResponse; apple: AppleProviderResponse; twitter: TwitterLoginResponse; oauth2: OAuth2LoginResponse; }

GoogleLoginResponse

GoogleLoginResponseOnline | GoogleLoginResponseOffline

LoginOptions

{ provider: 'facebook'; options: FacebookLoginOptions; } | { provider: 'google'; options: GoogleLoginOptions; } | { provider: 'apple'; options: AppleProviderOptions; } | { provider: 'twitter'; options: TwitterLoginOptions; } | { provider: 'oauth2'; options: OAuth2LoginOptions; }

Extract

Extract from T those types that are assignable to U

T extends U ? T : never

LoginResult

{ provider: 'facebook'; result: FacebookLoginResponse; } | { provider: 'google'; result: GoogleLoginResponse; } | { provider: 'apple'; result: AppleProviderResponse; } | { provider: 'twitter'; result: TwitterLoginResponse; } | { provider: 'oauth2'; result: OAuth2LoginResponse; }

ProviderSpecificCallResponseMap

{ 'facebook#getProfile': FacebookGetProfileResponse; 'facebook#requestTracking': FacebookRequestTrackingResponse; }

ProviderSpecificCall

'facebook#getProfile' | 'facebook#requestTracking'

ProviderSpecificCallOptionsMap

{ 'facebook#getProfile': FacebookGetProfileOptions; 'facebook#requestTracking': FacebookRequestTrackingOptions; }

FacebookRequestTrackingOptions

Record<string, never>

Privacy Manifest for App Developers

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

Google Sign-In Example

{
  "NSPrivacyCollectedDataTypes": [
    { "NSPrivacyCollectedDataType": "EmailAddress", "NSPrivacyCollectedDataTypeLinked": true, "NSPrivacyCollectedDataTypeTracking": false },
    { "NSPrivacyCollectedDataType": "Name", "NSPrivacyCollectedDataTypeLinked": true, "NSPrivacyCollectedDataTypeTracking": false },
    { "NSPrivacyCollectedDataType": "UserID", "NSPrivacyCollectedDataTypeLinked": true, "NSPrivacyCollectedDataTypeTracking": false }
  ]
}

Facebook Login Example

{
  "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 }
  ]
}

Apple Sign-In Example

{
  "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.

Combine facebook and google URL handler in AppDelegate.swift

    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
        // Called when the app was launched with a url. Feel free to add additional processing here,
        // but if you want the App API to support tracking app url opens, make sure to keep this call

        // Return true if the URL was handled by either Facebook or Google authentication
        // https://github.com/Cap-go/capacitor-social-login/blob/main/docs/setup_facebook.md#ios-setup
        // https://github.com/Cap-go/capacitor-social-login/blob/main/docs/setup_google.md#using-google-login-on-ios
        if FBSDKCoreKit.ApplicationDelegate.shared.application(
            app,
            open: url,
            sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String,
            annotation: options[UIApplication.OpenURLOptionsKey.annotation]
        ) || GIDSignIn.sharedInstance.handle(url) {
            return true
        }

        // If URL wasn't handled by auth services, pass it to Capacitor for processing
        return ApplicationDelegateProxy.shared.application(app, open: url, options: options)
    }

Credits

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.