magic_social_auth
Social sign-in for a Magic app, against the magic-starter-laravel backend. SocialAuth.driver(name).signIn() runs a native sheet (Google on iOS and Android, Apple on iOS) or a backend-hosted browser flow with PKCE (everything else) and answers a SocialAuthResult. The package never logs the app in: the caller (or the magic_starter bridge) does. social:install writes the config and the native edits, social:doctor checks them and prints the backend .env lines.
This skill covers magic_social_auth only. The Magic framework itself (container, facades, Auth, Http, Config) is the magic-framework skill; the backend routes and env live in magic-starter-laravel.
Install
flutter pub add magic_social_auth
dart run magic:dowel plugin:install magic_social_auth
dart run magic:dowel social:install \
--providers=google,apple,github,microsoft \
--google-ios-client-id=123-abc.apps.googleusercontent.com \
--google-server-client-id=123-def.apps.googleusercontent.com \
--ios-scheme=myapp \
--android-callback=https://auth.example.com/auth/social
dart run magic:dowel social:doctor
Requires Dart >=3.13, Flutter >=3.47, magic ^1.0.0 and a backend with the social-login feature on. social:install registers SocialAuthServiceProvider in lib/config/app.dart, writes lib/config/social_auth.dart and its configFactories entry, edits Info.plist, the entitlements, AndroidManifest.xml and web/auth.html for the providers you enable, and publishes the starter bridge when magic_starter is a dependency. Every flag is optional; --dry-run previews and --force overwrites a file that changed since the last install. Import only the barrel: package:magic_social_auth/magic_social_auth.dart.
Sign-in rules
- Register
SocialAuthServiceProviderbefore usingSocialAuth: it is not auto-registered, and the facade resolves thesocial_authsingleton it binds.social:installdoes it. SocialAuth.driver(name)caches per name. It throwsProviderNotConfiguredExceptionforenabled: falseandArgumentErrorfor a name that is neither built in nor registered withextend. Gate UI onSocialAuth.supports(name), which answersfalsefor both and for a platform the driver does not run on.- On the web call
signIn()straight from the tap handler with noawaitbefore it. The popup must open in the tap's own synchronous run, or the browser blocks it. - A driver answers a
SocialAuthResultand never creates a session. RunAuth.login({'token': result.token}, SocialAuth.manager.createUser(result.user!))yourself, after the app's user factory is registered (createUserdelegates toAuth.manager). - Check
result.isTwoFactorfirst: on a challenged sign-intokenanduserarenull, and you finish atauth/two-factor-challengewithtwoFactorToken. Tell the user whendeletionCancelledistrue. - Switch on
SocialAuthException.code, never onmessage, which the backend translates. A browser callback'serrorbecomes thecodetoo. SDK and browser failures carrysdk_error. - A
SocialAuthCancelledExceptionis not always the user's: Android reports a failed App Link verification and a misconfigured Google client (SHA-1, package name,server_client_id) as a cancel. Offer a retry, and stay quiet only whensupersededistrue, because the newer flow reports the outcome. - Apple's name arrives on the first authorisation only, in
AppleSignInResult.givenNameandfamilyName. Pass it to a profile update at once or it is lost. - A second browser flow on mobile while one is open throws
SocialAuthCancelledException(superseded: true). Disable the other buttons while one runs (SocialAuthButtons.loadingProvider).
Connect and confirm rules
connect(proof)links a provider to the signed-in account andconfirm()re-authenticates with a linked one. Both need the caller's bearer token, which magic'sHttpauth interceptor attaches, so the user must be signed in.proofis{'password': ...},{'code': ...}or{'confirmation_token': ...}, andnullfor a guest. Build it per call: every connect mints a new PKCE pair, link ticket and proof, and none is reusable.- On the web
connectopens the popup after anawaitand is blocked. CallbeginConnect(proof)first (the network half) and run the opener it returns from a second, explicit tap. confirm()answersconfirmationToken, a single-use proof; send it as{'confirmation_token': ...}to the gated call. A password-less, non-guest account has no password to type, which is what it is for.- There is no disconnect method. Unlinking is the backend's
DELETE user/social-accounts/{provider}, and a password-less account cannot remove its last way in (last_login_method).
Config and native rules
- The app config carries only
enabled,google.ios_client_id,google.server_client_idandcallback.iosandcallback.android, plus theSocialAuthButtonsoverrides per provider:label,icon_svg,icon_classandorder. Client secrets, scopes, tenants and the Apple key are the backend's. The browser flow starts at<network.drivers.api.base_url>/auth/social/{provider}/redirect, so that key must be the backend's API base. callback.iosandcallback.androidmust equal the backend'sMAGIC_STARTER_SOCIAL_IOS_REDIRECTandMAGIC_STARTER_SOCIAL_ANDROID_REDIRECT: the backend takes the redirect target only from its own config. There is no web key; the web lands on the app's ownauth.html.callback.iosis a custom scheme URL (myapp://auth/social), because an https callback needs iOS 17.4.callback.androidis an https App Link on a dedicated host that no other App Link filter in the app claims, or Android may open the wrong activity; the host serves/.well-known/assetlinks.json.- An empty callback that a flow needs throws a
SocialAuthExceptionnaming the key. GitHub and Microsoft need both mobile callbacks, Apple needs the Android one, Google and the web need none. - Google without
server_client_idreturns no ID token; the driver throwssdk_errorand logs the key. The key is the ID token's audience, so it is also in the backend'sMAGIC_STARTER_SOCIAL_GOOGLE_AUDIENCES. - A custom driver sends no nonce for Google. For Apple it sends
Nonce.hashedto Apple andNonce.rawto the backend, oneNonceper sheet. - Serve
auth.htmlwithout aCross-Origin-Opener-Policyheader. A same-origin one can severwindow.opener; the page then falls back to writing the result tolocalStorage, which the web flow reads. - Run
social:doctorafter any native or config change. Its checks are textual: keep provider entries andcallbackinlib/config/social_auth.dartflat maps of string and bool literals.
Buttons and sign-out rules
SocialAuthButtonsis built from Wind widgets and needs aWindThemeabove it (MagicApplicationprovides one).onPressed(provider)runs synchronously from the tap so a web popup can open.- Labels come from
trans('auth.sign_in_with')andtrans('auth.sign_up_with')with a:providerplaceholder. Without those translations passlabelBuilder. - The widget walks
social_auth.providers, so a custom provider needs its own entry there as well asSocialAuth.manager.extend(...). Register its icon and label withregisterProviderDefaults. SocialAuth.signOut()signs out only the drivers cached in this process. A session restored at boot cached none, so without themagic_starterbridge sign Google out by name on every transition to signed-out, or the next sign-in skips the account picker.
Recipes
Sign in and finish the session:
import 'package:magic/magic.dart';
import 'package:magic_social_auth/magic_social_auth.dart';
Future<void> signInWith(String provider) async {
try {
final SocialAuthResult result = await SocialAuth.driver(provider).signIn();
if (result.isTwoFactor) {
// Finish at auth/two-factor-challenge with result.twoFactorToken.
return;
}
await Auth.login(
{'token': result.token},
SocialAuth.manager.createUser(result.user!),
);
} on SocialAuthCancelledException catch (error) {
if (!error.superseded) {
// Offer a retry.
}
} on SocialAuthException catch (error) {
Log.error('Social sign-in refused: ${error.code}');
}
}
Connect a provider on the web, from two taps:
import 'package:magic_social_auth/magic_social_auth.dart';
Future<Future<SocialAuthResult> Function()> prepare(String password) {
return SocialAuth.driver('github').beginConnect({'password': password});
}
// In the next tap handler, an explicit "Continue to GitHub" button.
Future<SocialAuthResult> continueTo(Future<SocialAuthResult> Function() open) {
return open();
}
Get a step-up proof for a password-less account:
import 'package:magic_social_auth/magic_social_auth.dart';
Future<String?> proof() async {
final SocialAuthResult result = await SocialAuth.driver('google').confirm();
return result.confirmationToken;
}
Add a provider the backend hosts a flow for:
import 'package:magic_social_auth/magic_social_auth.dart';
void registerGitLab() {
SocialAuth.manager.extend(
'gitlab',
(config) => RedirectDriver('gitlab', config),
);
SocialAuth.manager.registerProviderDefaults(
'gitlab',
const SocialProviderDefaults(
label: 'GitLab',
iconSvg: '<svg viewBox="0 0 24 24"></svg>',
order: 5,
),
);
}
Sign Google out when the app signs out, without the starter bridge:
import 'dart:async';
import 'package:magic/magic.dart';
import 'package:magic_social_auth/magic_social_auth.dart';
void signGoogleOutOnSignOut() {
Auth.stateNotifier.addListener(() {
if (!Auth.check() && SocialAuth.supports('google')) {
unawaited(SocialAuth.driver('google').signOut());
}
});
}
Testing
No mocking library and no method-channel mock. Fake the platform through the @visibleForTesting seams by subclassing: GoogleDriver.initializeSdk, nativeSignIn and signOutSdk, AppleDriver.requestCredential, SocialFlow.authenticate. Stand in for the backend with Http.fake({'/auth/social/exchange': Http.response({...})}), and read recorded requests from the returned fake. In setUp() call MagicApp.reset(), Config.flush(), SocialAuthManager().forgetDrivers() and GoogleDriver.resetInitialization() (the SDK accepts one initialize per process). Force a platform with SocialAuthManager().platformOverride, and reset it to null in tearDown(). Wrap widget tests in MaterialApp and WindTheme(data: WindThemeData(), child: ...). Register a mock driver by contract inheritance (class MockDriver extends SocialDriver) through manager.extend.