Capacitor Social Login (@capgo/capacitor-social-login)

repository·main·Indexed 42 days ago

https://github.com/cap-go/capacitor-social-login

An all-in-one social authentication plugin for Capacitor (version 8.5.10) supporting Google, Apple, Facebook, Twitter/X, Telegram, LinkedIn, TikTok, and generic OAuth2 providers across Web, iOS, and Android.

Tokens
52.6K
Snippets
143
Records
176
Agent score
52%

What's inside Capacitor Social Login

  1. Supported Social Login Providers

    main

    The @capgo/capacitor-social-login plugin provides a unified interface for the following authentication providers across Web, iOS, and Android:

    • Google (using credential manager)
    • Apple (using OAuth on Android)
    • Facebook (using latest SDK)
    • Twitter/X (OAuth 2.0)
    • Telegram (Login Widget)
    • LinkedIn (OAuth 2.0 / OpenID Connect)
    • TikTok (Login Kit / OAuth2)
    • Generic OAuth2 (supports GitHub, Azure AD, Auth0, Okta, and any OAuth2-compliant server)
  2. Use ProviderSpecificCall for advanced provider features

    main

    The plugin allows calling specific methods on a provider using ProviderSpecificCall. These calls are mapped via ProviderSpecificCallResponseMap and ProviderSpecificCallOptionsMap to ensure correct input/output types.

    Available calls include:

    • facebook#getProfile
    • facebook#requestTracking
    • google#createRestoreCredential
    • google#getRestoreCredential
    • google#clearRestoreCredential
    // ProviderSpecificCall types
    'facebook#getProfile' | 'facebook#requestTracking' | 'google#createRestoreCredential' | 'google#getRestoreCredential' | 'google#clearRestoreCredential'
  3. Important notes on Auth Connect compatibility

    main

    When using the Auth Connect compatibility layer, keep the following in mind:

    • Implementation: The compatibility layer maps provider names and configuration to the internal OAuth2 engine; it is not a re-implementation of Ionic's native SDKs.
    • Refresh Tokens: To receive refresh tokens, you must include the offline_access scope if supported by your provider.
    • Bypassing Presets: You can always bypass the authConnect presets and configure providers directly using the oauth2 configuration field.
  4. Platform-specific OAuth2 behavior

    main

    The authentication experience varies by platform:

    • iOS: Uses ASWebAuthenticationSession for secure authentication.
    • Android: Uses an embedded WebView by default. To use Chrome Custom Tabs (RFC 8252) instead, set androidUseCustomTabs: true. This requires a deep-linkable redirectUrl and android:launchMode="singleTask" (or singleTop) on your main activity in AndroidManifest.xml.
    • Web: Opens a popup window for the OAuth flow.
  5. Understand LoginOptions and LoginResult types

    main

    The plugin uses discriminated unions to ensure type safety when performing logins and handling results.

    LoginOptions defines the provider and its specific configuration object. LoginResult maps the provider used to its corresponding response type.

    Supported providers include: facebook, google, apple, twitter, telegram, linkedin, tiktok, and oauth2.

    // Example of the LoginOptions shape
    // { provider: 'facebook'; options: FacebookLoginOptions; }
    // { provider: 'google'; options: GoogleLoginOptions; }
    // ...
    
    // Example of the LoginResult shape
    // { provider: 'facebook'; result: FacebookLoginResponse; }
    // { provider: 'google'; result: GoogleLoginResponse; }
    // ...
  6. Configure Google Auth Web Client ID for all platforms

    main

    The @capgo/capacitor-social-login plugin exclusively uses the Web Client ID for authentication across all platforms.

    • You must create a Web Client ID in the Google Cloud Console.
    • Use this Web Client ID in the webClientId field during initialization for all platforms.
    • Android Note: You still need to create an Android Client ID with your SHA1 for verification purposes, but the token from this ID will not be used by the plugin.
  7. Configure Android MainActivity for Social Login

    main

    Android requires manual updates to MainActivity.java to handle the Google login intent. You must implement ModifiedMainActivityForSocialLoginPlugin and override onActivityResult to pass the intent to the SocialLoginPlugin.

    import ee.forgr.capacitor.social.login.GoogleProvider;
    import ee.forgr.capacitor.social.login.SocialLoginPlugin;
    import ee.forgr.capacitor.social.login.ModifiedMainActivityForSocialLoginPlugin;
    import com.getcapacitor.PluginHandle;
    import com.getcapacitor.Plugin;
    import android.content.Intent;
    import android.util.Log;
    
    public class MainActivity extends BridgeActivity implements ModifiedMainActivityForSocialLoginPlugin {
    
      @Override
      public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if (requestCode >= GoogleProvider.REQUEST_AUTHORIZE_GOOGLE_MIN && requestCode < GoogleProvider.REQUEST_AUTHORIZE_GOOGLE_MAX) {
          PluginHandle pluginHandle = getBridge().getPlugin("SocialLogin");
          if (pluginHandle == null) {
            Log.i("Google Activity Result", "SocialLogin login handle is null");
            return;
          }
          Plugin plugin = pluginHandle.getInstance();
          if (!(plugin instanceof SocialLoginPlugin)) {
            Log.i("Google Activity Result", "SocialLogin plugin instance is not SocialLoginPlugin");
            return;
          }
          ((SocialLoginPlugin) plugin).handleGoogleLoginIntent(requestCode, data);
        }
      }
    
      public void IHaveModifiedTheMainActivityForTheUseWithSocialLoginPlugin() {}
    }
  8. Configure Keycloak with manual endpoint fallback

    main

    If OIDC discovery is blocked or your deployment does not expose metadata to the app, you must configure the endpoints directly. Ensure the base URL matches exactly what your Keycloak deployment publishes.

    const keycloakRealmUrl = 'https://keycloak.example.com/realms/my-realm';
    
    await SocialLogin.initialize({
      oauth2: {
        keycloak: {
          appId: 'your-keycloak-client-id',
          authorizationBaseUrl: `${keycloakRealmUrl}/protocol/openid-connect/auth`,
          accessTokenEndpoint: `${keycloakRealmUrl}/protocol/openid-connect/token`,
          redirectUrl: 'myapp://oauth/keycloak',
          scope: 'openid profile email',
          pkceEnabled: true,
          resourceUrl: `${keycloakRealmUrl}/protocol/openid-connect/userinfo`,
          logoutUrl: `${keycloakRealmUrl}/protocol/openid-connect/logout`,
        },
      },
    });
  9. Migrate from @codetrix-studio/capacitor-google-auth to @capgo/capacitor-social-login

    main

    To migrate from the legacy @codetrix-studio/capacitor-google-auth package to @capgo/capacitor-social-login, follow these steps:

    1. Uninstall the old package:

      npm uninstall @codetrix-studio/capacitor-google-auth
    2. Install the new package and sync Capacitor:

      npm install @capgo/capacitor-social-login
      npx cap sync
    3. Update Imports: Replace GoogleAuth with SocialLogin.

    4. Update Initialization: The initialization structure has changed. You must now pass a provider-specific object (e.g., google) to SocialLogin.initialize. Note that mode: 'offline' replaces the old grantOfflineAccess: true.

    5. Update Sign In Calls: Use SocialLogin.login({ provider: 'google', options: { ... } }) instead of GoogleAuth.signIn().

    npm uninstall @codetrix-studio/capacitor-google-auth
    npm install @capgo/capacitor-social-login
    npx cap sync
  10. Configure LinkedIn Login

    main

    LinkedIn login is a wrapper around OpenID Connect. You must register a web app in the LinkedIn Developer Portal with the Sign In with LinkedIn using OpenID Connect product enabled.

    Configuration

    • clientId: Your LinkedIn client ID.
    • redirectUrl: The redirect URL.
    • clientSecret: (Optional) Only if your LinkedIn app is configured as a confidential client.
    await SocialLogin.initialize({
      linkedin: {
        clientId: 'your-linkedin-client-id',
        redirectUrl: 'https://your-app.example/auth/linkedin',
      },
    });
    
    const res = await SocialLogin.login({ provider: 'linkedin' });
    console.log(res.result.accessToken?.token);
    console.log(res.result.resourceData); // LinkedIn userinfo payload
    await SocialLogin.initialize({
      linkedin: {
        clientId: 'your-linkedin-client-id',
        redirectUrl: 'https://your-app.example/auth/linkedin',
      },
    });
    
    const res = await SocialLogin.login({
      provider: 'linkedin',
      options: {},
    });
    
    console.log(res.result.accessToken?.token);
    console.log(res.result.resourceData);
  11. Configure Apple Login for Android

    main

    On Android, Apple login uses the web SDK and requires a server to handle the callback. You must call SocialLogin.initialize with the apple provider configuration before attempting to login.

    await SocialLogin.initialize({
      apple: {
        clientId: 'your-client-id',
        redirectUrl: 'your-redirect-url',
      },
    });
    
    const res = await SocialLogin.login({
      provider: 'apple',
      options: {
        scopes: ['email', 'name'],
      },
    });