### Minimal Descope SDK Setup Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/configuration.md Basic initialization of the Descope SDK with only the required project ID. This is the simplest way to get started. ```dart void main() { Descope.setup('my-project-id'); runApp(MyApp()); } ``` -------------------------------- ### start Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/authentication-methods.md Starts an OAuth authentication flow by returning an authorization URL. This is the first step in authenticating via OAuth providers. ```APIDOC ## start() ### Description Starts an OAuth authentication flow and returns the authorization URL. ### Method Future ### Parameters #### Path Parameters - **provider** (OAuthProvider) - Required - Provider like `OAuthProvider.google`, `OAuthProvider.apple`, etc. - **redirectUrl** (String?) - Optional - URL to redirect to after OAuth (overrides console config) - **options** (SignInOptions?) - Optional - Step-up, MFA, or custom claims ### Response #### Success Response - **String**: The OAuth authorization URL. #### Error Response - **DescopeException**: Thrown if an error occurs during the process. ### Example ```dart import 'package:flutter_web_auth/flutter_web_auth.dart'; final authUrl = await Descope.oauth.start( provider: OAuthProvider.google, redirectUrl: 'exampleauthschema://my-app.com/handle-oauth', ); final result = await FlutterWebAuth.authenticate( url: authUrl, callbackUrlScheme: 'exampleauthschema', ); final code = Uri.parse(result).queryParameters['code']; ``` ``` -------------------------------- ### DescopeFlowConfig Example Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/flows.md Example demonstrating how to initialize `DescopeFlowConfig` with common parameters like URL, native OAuth providers, and redirect URLs. ```dart final config = DescopeFlowConfig( url: 'https://api.descope.com/login/my-project-id?flow=sign-in', androidOAuthNativeProvider: 'google', iosOAuthNativeProvider: 'apple', magicLinkRedirect: 'https://myapp.example.com/magiclink', oauthRedirect: 'https://myapp.example.com/oauth', ); ``` -------------------------------- ### DescopeFlowConfig.hosted Example Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/flows.md Example of using the `hosted` factory constructor to configure a flow with native OAuth providers and a magic link redirect. ```dart final config = DescopeFlowConfig.hosted('sign-in') ..androidOAuthNativeProvider = 'google' ..iosOAuthNativeProvider = 'apple' ..magicLinkRedirect = 'https://myapp.example.com/magiclink'; ``` -------------------------------- ### DescopeFlowCallbacks Example Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/flows.md Example of implementing DescopeFlowCallbacks to handle flow events like readiness, successful authentication, and errors. ```dart final callbacks = DescopeFlowCallbacks( onReady: () { print('Flow is ready to display'); // Hide loading spinner }, onSuccess: (authResponse) { print('User authenticated: ${authResponse.user.email}'); final session = DescopeSession.fromAuthenticationResponse(authResponse); Descope.sessionManager.manageSession(session); // Navigate to home screen }, onError: (error) { print('Flow error: ${error.desc}'); if (error == DescopeException.flowCancelled) { print('User cancelled the flow'); } else { // Show error to user } }, ); ``` -------------------------------- ### Start OAuth Authentication Flow Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/authentication-methods.md Initiate an OAuth flow by calling `start` with the desired provider and an optional redirect URL. This method returns the authorization URL that the user needs to be redirected to. ```dart Future start({ required OAuthProvider provider, String? redirectUrl, SignInOptions? options, }) ``` ```dart import 'package:flutter_web_auth/flutter_web_auth.dart'; final authUrl = await Descope.oauth.start( provider: OAuthProvider.google, redirectUrl: 'exampleauthschema://my-app.com/handle-oauth', ); final result = await FlutterWebAuth.authenticate( url: authUrl, callbackUrlScheme: 'exampleauthschema', ); final code = Uri.parse(result).queryParameters['code']; ``` -------------------------------- ### Debug Logger Output Example Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/configuration.md An example of the output generated by the debug logger, showing SDK operations and responses. This helps in understanding the SDK's internal workings. ```text [DescopeFlutter] Making authentication request [DescopeFlutter] Response received: 200 OK [DescopeFlutter] Session refreshed successfully ``` -------------------------------- ### SSO Start Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/authentication-methods.md Initiates the Single Sign-On (SSO) flow by generating an authorization URL. This method is used to start the SSO process for a user. ```APIDOC ## start() ### Description Starts an SSO flow and returns the authorization URL. ### Method Future ### Parameters #### Path Parameters - **emailOrTenantId** (String) - Required - User's email or tenant ID - **redirectUrl** (String?) - Optional - URL to redirect to (overrides console config) - **options** (SignInOptions?) - Optional - Sign-in options ### Response #### Success Response - **String** - SSO authorization URL ### Throws - DescopeException ### Example ```dart final authUrl = await Descope.sso.start( emailOrTenantId: 'user@company.com', redirectUrl: 'exampleauthschema://my-app.com/handle-sso', ); ``` ``` -------------------------------- ### Example usage of onRefresh callback Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/storage-and-lifecycle.md This example shows how to call the `onRefresh` callback after a session has been successfully refreshed, signaling the session manager to save the new tokens. ```dart if (refreshed) { onRefresh?.call(); // Notify manager to save } ``` -------------------------------- ### Custom DescopeSdk Instance Configuration Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/configuration.md Example of creating and configuring a custom DescopeSdk instance with a specific base URL and logger. ```dart final customSdk = DescopeSdk('my-project-id', (config) { config.baseUrl = 'https://auth.mycompany.com'; config.logger = DescopeLogger.debugLogger; }); // Use custom SDK instance await customSdk.otp.signUp( method: DeliveryMethod.email, loginId: 'user@example.com', ); // Or set it as the default Descope.setup('my-project-id'); Descope.sessionManager = DescopeSessionManager( SessionStorage(projectId: 'my-project-id'), SessionLifecycle(customSdk.auth), ); ``` -------------------------------- ### Example Custom Session Storage Implementation Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/storage-and-lifecycle.md Implement DescopeSessionStorage to customize session persistence. This example shows how to save, load, and remove session data using a custom storage solution. ```dart class CustomStorage extends DescopeSessionStorage { @override Future saveSession(DescopeSession session) async { // Save session to your storage await MyStorage.instance.setSession({ 'sessionJwt': session.sessionJwt, 'refreshJwt': session.refreshJwt, 'user': { 'userId': session.user.userId, 'email': session.user.email, }, }); } @override Future loadSession() async { final data = await MyStorage.instance.getSession(); if (data == null) { return null; } try { return DescopeSession.fromJwt( data['sessionJwt'], data['refreshJwt'], DescopeUser( // Reconstruct user from stored data userId: data['user']['userId'], // ... other fields ), ); } catch (e) { // Storage corrupted, return null return null; } } @override Future removeSession() async { await MyStorage.instance.clearSession(); } } ``` -------------------------------- ### Flutter Descope Flow Integration Example Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/flows.md An example of how to implement a sign-in screen using DescopeFlowView in a Flutter application. It includes state management for loading, handling authentication success and errors, and setting up deep link handling. ```dart class FlowScreen extends StatefulWidget { @override State createState() => _FlowScreenState(); } class _FlowScreenState extends State { bool _loading = true; final _controller = DescopeFlowController(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Sign In')), body: Stack( children: [ Positioned.fill( child: AnimatedOpacity( opacity: _loading ? 0.0 : 1.0, duration: Duration(milliseconds: 150), child: DescopeFlowView( config: DescopeFlowConfig( url: 'https://api.descope.com/login/my-project-id?flow=sign-in', ), callbacks: DescopeFlowCallbacks( onReady: () => setState(() => _loading = false), onSuccess: (response) { final session = DescopeSession.fromAuthenticationResponse(response); Descope.sessionManager.manageSession(session); Navigator.pop(context); }, onError: (error) { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('Flow error: ${error.message}')), ); }, ), controller: _controller, ), ), ), if (_loading) Center(child: CircularProgressIndicator()), ], ), ); } @override void initState() { super.initState(); // Handle deep links _listenForDeepLinks(); } void _listenForDeepLinks() { // Use flutter_app_links or similar to listen for deep links // When received, call: _controller.resumeFromDeepLink(uri) } } ``` -------------------------------- ### Descope SDK Setup with Logging Enabled Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/configuration.md Initializes the Descope SDK and enables debug logging for detailed SDK operation information. This is recommended for development and debugging. ```dart void main() { Descope.setup('my-project-id', (config) { // Enable debug logging (shows all SDK operations) config.logger = DescopeLogger.debugLogger; }); runApp(MyApp()); } ``` -------------------------------- ### Load Saved Session on App Start Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/session-management.md Load any previously saved session from secure storage when the application starts. This allows users to resume their authenticated state. ```dart void main() async { WidgetsFlutterBinding.ensureInitialized(); Descope.setup('my-project-id'); // Load any saved session from previous app launch await Descope.sessionManager.loadSession(); final session = Descope.sessionManager.session; if (session != null) { print('User logged in: ${session.user.userId}'); } runApp(MyApp()); } ``` -------------------------------- ### Example implementation of refreshSessionIfNeeded Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/storage-and-lifecycle.md This example demonstrates how to implement `refreshSessionIfNeeded` by checking session expiry and performing a refresh. It updates the session with new tokens upon successful refresh. ```dart @override Future refreshSessionIfNeeded() async { final session = this.session; if (session != null) { // Check if session expires within 2 minutes final expiresAt = session.sessionToken.expiresAt; if (expiresAt != null) { final now = DateTime.now(); final refreshThreshold = Duration(minutes: 2); if (now.add(refreshThreshold).isAfter(expiresAt)) { // Refresh needed final response = await _auth.refreshSession(session.refreshJwt); session.updateTokens(response); } } } } ``` -------------------------------- ### Descope SDK Setup with Testing HTTP Client Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/configuration.md Initializes the Descope SDK and injects a custom HTTP client for testing purposes. This allows mocking network responses. ```dart class MockHttpClient extends DescopeNetworkClient { @override Future sendRequest(http.Request request) async { // Mock response for testing return http.Response('{"key": "value"}', 200); } } void main() { Descope.setup('my-project-id', (config) { config.networkClient = MockHttpClient(); }); runApp(MyApp()); } ``` -------------------------------- ### Configure Unit Tests with Google Test Source: https://github.com/descope/descope-flutter/blob/main/windows/CMakeLists.txt Sets up unit tests using Google Test, including fetching the dependency and configuring the test executable. Tests are only built when the example is built. ```cmake # === Tests === # These unit tests can be run from a terminal after building the example, or # from Visual Studio after opening the generated solution file. # Only enable test builds when building the example (which sets this variable) # so that plugin clients aren't building the tests. if (${include_${PROJECT_NAME}_tests}) set(TEST_RUNNER "${PROJECT_NAME}_test") enable_testing() # Add the Google Test dependency. include(FetchContent) FetchContent_Declare( googletest URL https://github.com/google/googletest/archive/release-1.11.0.zip ) # Prevent overriding the parent project's compiler/linker settings set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) # Disable install commands for gtest so it doesn't end up in the bundle. set(INSTALL_GTEST OFF CACHE BOOL "Disable installation of googletest" FORCE) FetchContent_MakeAvailable(googletest) # The plugin's C API is not very useful for unit testing, so build the sources # directly into the test binary rather than using the DLL. add_executable(${TEST_RUNNER} test/descope_plugin_test.cpp ${PLUGIN_SOURCES} ) apply_standard_settings(${TEST_RUNNER}) target_include_directories(${TEST_RUNNER} PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}") target_link_libraries(${TEST_RUNNER} PRIVATE flutter_wrapper_plugin) target_link_libraries(${TEST_RUNNER} PRIVATE gtest_main gmock) # flutter_wrapper_plugin has link dependencies on the Flutter DLL. add_custom_command(TARGET ${TEST_RUNNER} POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different "${FLUTTER_LIBRARY}" $ ) # Enable automatic test discovery. include(GoogleTest) gtest_discover_tests(${TEST_RUNNER}) endif() ``` -------------------------------- ### SessionStorage Constructor Example Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/storage-and-lifecycle.md Instantiate the default SessionStorage with a project ID and an optional custom store. Auto-detection handles platform-specific storage. ```dart final storage = SessionStorage( projectId: 'my-project-id', store: CustomStore(), ); ``` -------------------------------- ### Start SSO/SAML Flow Source: https://github.com/descope/descope-flutter/blob/main/README.md Initiates a SAML or Single Sign On flow for a specific tenant. The redirect URL is optional if configured globally. ```dart // Choose which tenant to log into // If configured globally, the return URL is optional. If provided however, it will be used // instead of any global configuration. final authUrl = await Descope.sso.start(emailOrTenantId: 'my-tenant-ID', redirectUrl: 'exampleauthschema://my-app.com/handle-saml'); ``` -------------------------------- ### Start OAuth Flow with Google Source: https://github.com/descope/descope-flutter/blob/main/README.md Initiates an OAuth flow for Google authentication. The redirect URL is optional if configured globally. ```dart import 'package:flutter_web_auth/flutter_web_auth.dart'; // Choose an oauth provider out of the supported providers // If configured globally, the redirect URL is optional. If provided however, it will be used // instead of any global configuration. final authUrl = await Descope.oauth.start(provider: OAuthProvider.google, redirectUrl: 'exampleauthschema://my-app.com/handle-oauth'); ``` -------------------------------- ### Custom Session Storage Implementation Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/configuration.md Example of implementing a custom session storage backend by extending SessionStorageStore. This allows for custom storage solutions. ```dart class CustomSessionStore extends SessionStorageStore { @override Future saveItem({ required String key, required String data, }) async { // Save to your custom storage await MyCustomStorage.set(key, data); } @override Future loadItem(String key) async { // Load from your custom storage return await MyCustomStorage.get(key); } @override Future removeItem(String key) async { // Delete from your custom storage await MyCustomStorage.delete(key); } } // Use custom storage final storage = SessionStorage( projectId: 'my-project-id', store: CustomSessionStore(), ); final lifecycle = SessionLifecycle(Descope.auth); final manager = DescopeSessionManager(storage, lifecycle); Descope.sessionManager = manager; ``` -------------------------------- ### Descope SDK Setup with Custom Logger Implementation Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/configuration.md Initializes the Descope SDK and provides a custom logger implementation for tailored logging behavior. This allows integration with custom logging services. ```dart class MyLogger extends DescopeLogger { @override void output({ required int level, required String message, required List values, }) { final levelName = level == DescopeLogger.error ? 'ERROR' : level == DescopeLogger.info ? 'INFO' : 'DEBUG'; // Send to your logging service MyLoggingService.log('[$levelName] $message'); if (values.isNotEmpty) { MyLoggingService.log('Values: $values'); } } } void main() { Descope.setup('my-project-id', (config) { config.logger = MyLogger(); }); runApp(MyApp()); } ``` -------------------------------- ### Sign Up or In with Passkey Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/authentication-methods.md A convenient method that either signs in an existing user with their passkey or creates a new account and prompts for passkey setup if the user does not exist. Supports additional sign-in options. ```dart Future signUpOrIn({ required String loginId, SignInOptions? options, }) { // ... implementation details ... } ``` -------------------------------- ### native Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/authentication-methods.md Authenticates using native Sign In with Apple or Google dialogs. This method is platform-specific and requires additional setup. ```APIDOC ## native() ### Description Authenticates using native Sign In with Apple (iOS) or Google (Android) dialogs. ### Method Future ### Parameters #### Path Parameters - **provider** (OAuthProvider) - Required - Named provider configured for native auth - **options** (SignInOptions?) - Optional - MFA or step-up options ### Response #### Success Response - **AuthenticationResponse**: The response containing authentication details. #### Error Response - **DescopeException**: Thrown if the native authentication is cancelled (e.g., `oauthNativeCancelled`). ### Note Requires platform-specific setup. See README for iOS/Android configuration. ### Example ```dart if (Platform.isIOS) { final response = await Descope.oauth.native( provider: OAuthProvider.apple, ); final session = DescopeSession.fromAuthenticationResponse(response); Descope.sessionManager.manageSession(session); } ``` ``` -------------------------------- ### Descope SDK Setup with Custom Base URL Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/configuration.md Initializes the Descope SDK and configures a custom base URL for API requests. This is useful when using CNAME records. ```dart void main() { Descope.setup('my-project-id', (config) { config.baseUrl = 'https://auth.mycompany.com'; }); runApp(MyApp()); } ``` -------------------------------- ### Start SSO Flow Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/authentication-methods.md Initiates an SSO flow and returns the authorization URL. Use this to begin the single sign-on process for users. ```dart final authUrl = await Descope.sso.start( emailOrTenantId: 'user@company.com', redirectUrl: 'exampleauthschema://my-app.com/handle-sso', ); ``` -------------------------------- ### Create Custom OAuth Provider Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/types.md Example of how to define a custom OAuth provider by providing its name. This is useful for integrating with providers not explicitly supported out-of-the-box. ```dart final customProvider = OAuthProvider.named("my-custom-provider"); ``` -------------------------------- ### Get Permissions for Tenant Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/session-management.md Returns the list of permissions granted to the user for a specific tenant. If no tenant is provided, it defaults to the current tenant context. ```dart List permissions([String? tenant]) ``` ```dart final perms = session.permissions('tenant-123'); if (perms.contains('admin')) { print('User is an admin'); } ``` -------------------------------- ### Standard HTTP Bearer Authorization Header Format Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/http-extensions.md Illustrates the standard HTTP Bearer token format used for authorization, including an example token. ```text Authorization: Bearer ``` ```text Authorization: Bearer eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2OTM0NzU5MzQsImlhdCI6MTY5MzQ3MjMzNCwiaXNzIjoiaHR0cHM6Ly9jb25jZXJ0LmRlc2NvcGUuY29tIiwic3ViIjoidXNlci1iZjgzYzAwYi1kYWY4LTRiNGEtOWY3ZC1iZWQwMDAwMDAwMDEiLCJhdWQiOlsiZGVzY29wZS1jb25jZXJ0Il0sImF6cCI6ImFwaS1iZjgzYzAwYi1kYWY4LTRiNGEtOWY3ZC1iZWQwMDAwMDAwMDEifQ.signature ``` -------------------------------- ### Get Roles for Tenant Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/session-management.md Returns the list of roles assigned to the user for a specific tenant. If no tenant is provided, it defaults to the current tenant context. ```dart List roles([String? tenant]) ``` ```dart final roles = session.roles(); if (roles.contains('admin')) { print('User has admin role'); } ``` -------------------------------- ### Setting Client Inputs for Flow Configuration Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/flows.md Customize flow behavior by passing JSON-serializable data using the `clientInputs` property. This example sets a default email and company name. ```dart config.clientInputs = { 'defaultEmail': 'user@example.com', 'companyName': 'Acme Inc', }; ``` -------------------------------- ### signUp() Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/authentication-methods.md Creates a new user and prompts them to create a passkey. This method is used for onboarding new users with passkey authentication. ```APIDOC ## signUp() ### Description Creates a new user and prompts them to create a passkey. ### Method Future ### Parameters #### Path Parameters - **loginId** (String) - Required - Unique identifier - **details** (SignUpDetails?) - Optional - Additional user details ### Returns Future - An object containing authentication details. ### Throws DescopeException - e.g., `passkeyCancelled` ### Example ```dart try { final authResponse = await Descope.passkey.signUp(loginId: 'user@example.com'); final session = DescopeSession.fromAuthenticationResponse(authResponse); Descope.sessionManager.manageSession(session); } on DescopeException catch (e) { if (e == DescopeException.passkeyCancelled) { print('User cancelled passkey creation'); } } ``` ``` -------------------------------- ### Descope.setup() Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/descope-sdk.md Initializes the Descope SDK with your project ID. This is a required first step before using any other SDK functionality. It can also optionally configure base URL, logger, and network client. ```APIDOC ## Descope.setup() ### Description Initializes the Descope SDK with your project ID. This is a required first step before using any other SDK functionality. It can also optionally configure base URL, logger, and network client. ### Method Signature `static void setup(String projectId, [Function(DescopeConfig)? configure])` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Parameters * **projectId** (String) - Required - The project ID from the Descope console at https://app.descope.com/settings/project * **configure** (Function(DescopeConfig)?) - Optional - Optional callback to configure SDK behavior (baseUrl, logger, networkClient) ### Returns void ### Throws DescopeException if configuration is invalid ### Example ```dart import 'package:descope/descope.dart'; // Minimal setup Descope.setup('my-project-id'); // With custom configuration Descope.setup('my-project-id', (config) { config.baseUrl = 'https://my.app.com'; config.logger = DescopeLogger.debugLogger; }); ``` ``` -------------------------------- ### Load Previous Session on App Start Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/README.md Load any saved session from previous app launches to maintain user authentication state. This should be called after initializing the SDK and ensuring the Flutter binding is initialized. ```dart void main() async { WidgetsFlutterBinding.ensureInitialized(); Descope.setup('your-project-id'); // Load any saved session from previous app launch await Descope.sessionManager.loadSession(); final session = Descope.sessionManager.session; if (session != null) { // User is already authenticated } runApp(MyApp()); } ``` -------------------------------- ### Sign Up with Passkey Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/authentication-methods.md Create a new user account and prompt them to set up a passkey for future authentication. Handles potential user cancellation during the passkey creation process. ```dart Future signUp({ required String loginId, SignUpDetails? details, }) { // ... implementation details ... } try { final authResponse = await Descope.passkey.signUp(loginId: 'user@example.com'); final session = DescopeSession.fromAuthenticationResponse(authResponse); Descope.sessionManager.manageSession(session); } on DescopeException catch (e) { if (e == DescopeException.passkeyCancelled) { print('User cancelled passkey creation'); } } ``` -------------------------------- ### DescopeOtp.signUp() Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/authentication-methods.md Sends an OTP to a new user and initiates sign up. ```APIDOC ## DescopeOtp.signUp() ### Description Sends an OTP to a new user and initiates sign up. ### Method Signature ```dart Future signUp({ required DeliveryMethod method, required String loginId, SignUpDetails? details, }) ``` ### Parameters #### Path Parameters - **method** (DeliveryMethod) - Required - `DeliveryMethod.email`, `DeliveryMethod.sms`, or `DeliveryMethod.whatsapp` - **loginId** (String) - Required - Email, phone number, or username (must match method) - **details** (SignUpDetails?) - Optional - Additional user details (name, email, phone, givenName, middleName, familyName) ### Returns Future — Masked email/phone indicating where OTP was sent ### Throws DescopeException with error code (e.g., `invalidRequest`) ### Example ```dart try { final masked = await Descope.otp.signUp( method: DeliveryMethod.email, loginId: 'user@example.com', details: SignUpDetails(name: 'John Doe'), ); print('OTP sent to: $masked'); } on DescopeException catch (e) { print('Sign up failed: ${e.message}'); } ``` ``` -------------------------------- ### Basic DescopeFlowView Integration in Flutter Source: https://github.com/descope/descope-flutter/blob/main/README.md This snippet shows a minimal configuration for displaying a `DescopeFlowView` within a Flutter screen. It includes essential parameters for flow configuration and handling of ready, success, and error callbacks. Use this as a starting point for integrating Descope authentication flows. ```dart class _NativeFlowScreenState extends State { bool _loading = true; @override Widget build(BuildContext context) { final bg = Theme.of(context).colorScheme.surface; return Scaffold( backgroundColor: bg, appBar: AppBar( backgroundColor: Theme.of(context).colorScheme.inversePrimary, title: const Text('Descope Flow View Example'), leading: IconButton( icon: const Icon(Icons.close), onPressed: () => context.pop(), tooltip: 'Close', ), ), body: SafeArea( child: Stack( children: [ // Solid background to avoid black flash Positioned.fill(child: ColoredBox(color: bg)), // Keep the platform view mounted but invisible until ready Positioned.fill( child: AnimatedOpacity( opacity: _loading ? 0.0 : 1.0, duration: const Duration(milliseconds: 150), child: DescopeFlowView( config: DescopeFlowConfig( url: '', // If using Descope hosted flows, you can provide the flow ID directly: // use DescopeFlowConfig.hosted('') instead of the constructor above // Optional parameters - will be required according to the flow you're using // and the authentication methods it contains androidOAuthNativeProvider: 'google', // an example supporting native Google Sign In on Android iosOAuthNativeProvider: 'apple', // an example supporting native Sign In with Apple on iOS oauthRedirect: 'https://YOUR_DEEP_LINK_URL/oauth', // android only - needs to match the app link you configured in your manifest magicLinkRedirect: 'https://YOUR_DEEP_LINK_URL/magiclink', // needs to match the app link you configured in your manifest or associated domain ), callbacks: DescopeFlowCallbacks( onReady: () { // simple reveal animation when the flow is ready if (!mounted) return; setState(() => _loading = false); }, onSuccess: (AuthenticationResponse res) { // handle the successful authentication response, assuming the model calls // something along the lines of: // final session = DescopeSession.fromAuthenticationResponse(res); // Descope.sessionManager.manageSession(session); model.handleAuthResponse(res); if (context.mounted) context.pop(); }, onError: (DescopeException e) { // handle any errors that might occur during the flow. // errors generally mean that the flow is unrecoverable and // needs to be restarted. model.handleError(e); if (context.mounted) context.pop(); }, ), controller: model.descopeFlowController, ), ), ), if (_loading) const Center(child: CircularProgressIndicator()), ], ), ), ); } } ``` -------------------------------- ### signUpOrIn() Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/authentication-methods.md Authenticates a user or creates a new one if they don't exist. This is a convenient method for both new and returning users. ```APIDOC ## signUpOrIn() ### Description Authenticates a user or creates a new one if they don't exist. ### Method Future ### Parameters #### Path Parameters - **loginId** (String) - Required - User's login ID - **options** (SignInOptions?) - Optional - Sign-in options ### Returns Future - An object containing authentication details. ### Throws DescopeException ### Example ```dart try { final authResponse = await Descope.passkey.signUpOrIn(loginId: 'user@example.com'); final session = DescopeSession.fromAuthenticationResponse(authResponse); Descope.sessionManager.manageSession(session); } on DescopeException catch (e) { // Handle exceptions } ``` ``` -------------------------------- ### Native OAuth Authentication (iOS/Android) Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/authentication-methods.md Authenticate using native Sign In with Apple or Google dialogs by calling the `native` method. This requires platform-specific setup and is recommended for a seamless user experience on mobile. ```dart Future native({ required OAuthProvider provider, SignInOptions? options, }) ``` ```dart if (Platform.isIOS) { final response = await Descope.oauth.native( provider: OAuthProvider.apple, ); final session = DescopeSession.fromAuthenticationResponse(response); Descope.sessionManager.manageSession(session); } ``` -------------------------------- ### signUpOrIn Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/authentication-methods.md Sends an OTP for sign in or creates a new user if they don't exist. It requires a delivery method and a login ID, with optional sign-in options. ```APIDOC ## signUpOrIn() ### Description Sends an OTP for sign in or creates a new user if they don't exist. ### Method Signature ```dart Future signUpOrIn({ required DeliveryMethod method, required String loginId, SignInOptions? options, }) ``` ### Parameters #### Path Parameters - **method** (DeliveryMethod) - Required - Delivery method - **loginId** (String) - Required - Email, phone number, or username - **options** (SignInOptions?) - Optional - Sign-in options ### Returns Future — Masked delivery address ### Throws DescopeException ``` -------------------------------- ### Simple Authenticated GET Request Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/http-extensions.md Demonstrates making a GET request to a protected API endpoint after adding Descope authentication. Handles successful responses and common error codes like 401 Unauthorized. ```dart import 'package:http/http.dart' as http; import 'package:descope/descope.dart'; Future> fetchUserData() async { final request = http.Request( 'GET', Uri.parse('https://api.myapp.com/user/profile'), ); // Add Descope authentication await request.setAuthorization(Descope.sessionManager); // Send and decode response final response = await http.Client().send(request); if (response.statusCode == 200) { return jsonDecode(response.body) as Map; } else if (response.statusCode == 401) { throw Exception('Unauthorized - session invalid'); } else { throw Exception('Server error: ${response.statusCode}'); } } ``` -------------------------------- ### Sign Up with Password Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/authentication-methods.md Creates a new user account using email/username and password. Ensure the password meets the configured policy requirements. ```dart Future signUp({ required String loginId, required String password, SignUpDetails? details, }) ``` -------------------------------- ### DescopeToken.jwt Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/session-management.md Gets the raw JWT string from a DescopeToken. ```APIDOC ## DescopeToken.jwt ### Description The raw JWT string. ### Type String ``` -------------------------------- ### DescopeToken.customClaims Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/session-management.md Gets all custom claims in the token, excluding standard claims. ```APIDOC ## DescopeToken.customClaims ### Description All custom claims in the token (standard claims excluded). ### Type Map ``` -------------------------------- ### Configure Include Directories and Library Dependencies Source: https://github.com/descope/descope-flutter/blob/main/linux/CMakeLists.txt Specifies include directories for the plugin and links necessary libraries like 'flutter' and 'PkgConfig::GTK'. ```cmake target_include_directories(${PLUGIN_NAME} INTERFACE "${CMAKE_CURRENT_SOURCE_DIR}/include") target_link_libraries(${PLUGIN_NAME} PRIVATE flutter) target_link_libraries(${PLUGIN_NAME} PRIVATE PkgConfig::GTK) ``` -------------------------------- ### Get Raw JWT from DescopeToken Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/session-management.md Retrieves the raw JWT string from a DescopeToken. ```dart String get jwt ``` -------------------------------- ### Sign Up or In with Passkey Source: https://github.com/descope/descope-flutter/blob/main/README.md Initiates the passkey sign-up or sign-in flow. Handles potential cancellation and manages the session upon successful authentication. ```dart try { showLoading(true); final authResponse = await Descope.passkey.signUpOrIn(loginId: loginId); final session = DescopeSession.fromAuthenticationResponse(authResponse); Descope.sessionManager.manageSession(session); showHomeScreen() } on DescopeException catch (e) { if (e == DescopeException.passkeyCancelled) { showLoading(false) print("Authentication cancelled") } else { showError(error) } } ``` -------------------------------- ### Get Refresh JWT Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/session-management.md Retrieves the long-lived JWT string used for refreshing the session. ```dart String get refreshJwt ``` -------------------------------- ### DescopeToken.projectId Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/session-management.md Gets the Descope project ID (the "iss" claim) this token belongs to. ```APIDOC ## DescopeToken.projectId ### Description The "iss" (issuer) claim — the Descope project ID this token belongs to. ### Type String ``` -------------------------------- ### Get Roles for Tenant from DescopeToken Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/session-management.md Returns the list of roles present in the token for a specified tenant. ```dart List getRoles({required String? tenant}) ``` -------------------------------- ### Sign Up with Password Source: https://github.com/descope/descope-flutter/blob/main/README.md Signs up a new user with a login ID and password. Ensure password authentication is enabled in the Descope console. ```dart // Every user must have a loginID. All other user information is optional final authResponse = await Descope.password.signUp(loginId: 'desmond_c@mail.com', password: 'cleartext-password', details: SignUpDetails(name: 'Desmond Copeland')); ``` -------------------------------- ### Get Permissions for Tenant from DescopeToken Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/session-management.md Returns the list of permissions present in the token for a specified tenant. ```dart List getPermissions({required String? tenant}) ``` -------------------------------- ### DescopeToken.expiresAt Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/session-management.md Gets the expiration time (the "exp" claim) of the token, or null if it never expires. ```APIDOC ## DescopeToken.expiresAt ### Description The "exp" (expiration time) claim, or null if the token never expires. ### Type DateTime? ``` -------------------------------- ### DescopeToken.id Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/session-management.md Gets the unique user or access key ID (the "sub" claim) from a DescopeToken. ```APIDOC ## DescopeToken.id ### Description The "sub" (subject) claim — unique user or access key ID. ### Type String ``` -------------------------------- ### Get Project ID from DescopeToken Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/session-management.md Retrieves the Descope project ID (the 'iss' claim) associated with the token. ```dart String get projectId ``` -------------------------------- ### Sign Up with OTP (Email) Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/authentication-methods.md Initiates the sign-up process by sending a One-Time Password (OTP) via email. Requires a valid email address and optionally accepts additional user details. Returns a masked email address indicating where the OTP was sent. ```dart try { final masked = await Descope.otp.signUp( method: DeliveryMethod.email, loginId: 'user@example.com', details: SignUpDetails(name: 'John Doe'), ); print('OTP sent to: $masked'); } on DescopeException catch (e) { print('Sign up failed: ${e.message}'); } ``` -------------------------------- ### Get Session Claims Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/session-management.md Retrieves all custom claims from the session token, excluding standard JWT claims. ```dart Map get claims ``` ```dart final customClaim = session.claims['custom_field']; ``` -------------------------------- ### Get Session JWT Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/session-management.md Retrieves the short-lived JWT string for authenticated requests. Use this in the Authorization header. ```dart String get sessionJwt ``` ```dart final jwt = session.sessionJwt; // Use in Authorization header: 'Bearer $jwt' ``` -------------------------------- ### Sign Up with TOTP Source: https://github.com/descope/descope-flutter/blob/main/README.md Initiates the TOTP sign-up process, returning provisioning details like a QR code, URL, or key for the user's authenticator app. ```dart // Every user must have a loginID. All other user information is optional final totpResponse = await Descope.totp.signUp(loginId: 'desmond@descope.com', details: SignUpDetails(name: 'Desmond Copeland')); // Use one of the provided options to have the user add their credentials to the authenticator // totpResponse.provisioningUrl // totpResponse.image // totpResponse.key ``` -------------------------------- ### Get Current Session Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/session-management.md Retrieves the currently managed session object. Returns null if no session is active. ```dart if (Descope.sessionManager.session != null) { print('Logged in as: ${Descope.sessionManager.session!.user.email}'); } ``` -------------------------------- ### Setting stalenessCheckFrequency Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/storage-and-lifecycle.md Example of how to adjust the `stalenessCheckFrequency` to check for session refresh needs less frequently, such as every minute. ```dart lifecycle.stalenessCheckFrequency = Duration(minutes: 1); // Check every minute ``` -------------------------------- ### Apply Standard Build Settings Source: https://github.com/descope/descope-flutter/blob/main/linux/CMakeLists.txt Applies common build settings from the application-level CMakeLists.txt. This simplifies configuration for plugins. ```cmake apply_standard_settings(${PLUGIN_NAME}) ``` -------------------------------- ### Setting stalenessAllowedInterval Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/storage-and-lifecycle.md Example of how to customize the `stalenessAllowedInterval` to trigger session refresh earlier, for instance, 5 minutes before expiry. ```dart final lifecycle = SessionLifecycle(Descope.auth); lifecycle.stalenessAllowedInterval = Duration(minutes: 5); // Refresh 5 min before expiry ``` -------------------------------- ### signIn() Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/authentication-methods.md Authenticates an existing user with their passkey. This method is used for returning users to log in. ```APIDOC ## signIn() ### Description Authenticates an existing user with their passkey. ### Method Future ### Parameters #### Path Parameters - **loginId** (String) - Required - User's login ID - **options** (SignInOptions?) - Optional - MFA or step-up options ### Returns Future - An object containing authentication details. ### Throws DescopeException ### Example ```dart try { final authResponse = await Descope.passkey.signIn(loginId: 'user@example.com'); final session = DescopeSession.fromAuthenticationResponse(authResponse); Descope.sessionManager.manageSession(session); } on DescopeException catch (e) { // Handle exceptions } ``` ``` -------------------------------- ### Get Custom Claims from DescopeToken Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/session-management.md Retrieves all custom claims within the token, excluding standard JWT claims. ```dart Map get customClaims ``` -------------------------------- ### Get Expiration Time from DescopeToken Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/session-management.md Retrieves the expiration time ('exp' claim) of the token, or null if it never expires. ```dart DateTime? get expiresAt ``` -------------------------------- ### Get User ID from DescopeToken Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/session-management.md Retrieves the unique user or access key ID (the 'sub' claim) from a DescopeToken. ```dart String get id ``` -------------------------------- ### OTP Authentication - Sign Up Source: https://github.com/descope/descope-flutter/blob/main/README.md Initiate OTP authentication by sending a code to a specified email address. This is the first step in the OTP sign-up process. ```dart // sends an OTP code to the given email address await Descope.otp.signUp(method: DeliveryMethod.email, loginId: 'andy@example.com'); ``` -------------------------------- ### Initialize Descope and Load Session in main() Source: https://github.com/descope/descope-flutter/blob/main/README.md Initialize the Descope SDK and load the user session in the main function before running the application. Ensure widget bindings are initialized first. ```dart void main() async { WidgetsFlutterBinding.ensureInitialized(); Descope.setup('...'); await Descope.sessionManager.loadSession(); final session = Descope.sessionManager.session; if (session != null) { print('User is logged in: ${session.user}'); } runApp( ... ); } ``` -------------------------------- ### Project and Plugin Configuration Source: https://github.com/descope/descope-flutter/blob/main/linux/CMakeLists.txt Defines the project name and the specific plugin name. These are crucial for build system identification. ```cmake set(PROJECT_NAME "descope") project(${PROJECT_NAME} LANGUAGES CXX) set(PLUGIN_NAME "descope_plugin") ``` -------------------------------- ### Password Sign Up Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/authentication-methods.md Creates a new user account using email/username and password. This method enforces password policies configured in the Descope console. ```APIDOC ## signUp() ### Description Creates a new user with a password. ### Method Future ### Parameters #### Path Parameters - **loginId** (String) - Required - Unique identifier (email, username, etc.) - **password** (String) - Required - Password (must conform to policy) - **details** (SignUpDetails?) - Optional - Additional user details ### Response #### Success Response - **AuthenticationResponse** ### Throws - DescopeException ``` -------------------------------- ### Handle Passkey Cancelled Error Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/errors.md Catch the error when a user cancels the passkey authentication process, for example, by dismissing a biometric prompt. ```dart try { final response = await Descope.passkey.signUp(loginId: 'user@example.com'); } on DescopeException catch (e) { if (e == DescopeException.passkeyCancelled) { print('User cancelled passkey creation'); } } ``` -------------------------------- ### Initialize Descope SDK Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/descope-sdk.md Initializes the Descope SDK with your project ID. Optionally configure base URL, logger, and network client. ```dart import 'package:descope/descope.dart'; // Minimal setup Descope.setup('my-project-id'); // With custom configuration Descope.setup('my-project-id', (config) { config.baseUrl = 'https://my.app.com'; config.logger = DescopeLogger.debugLogger; }); ``` -------------------------------- ### DescopeOtp.signIn() Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/authentication-methods.md Sends an OTP to an existing user for sign in. ```APIDOC ## DescopeOtp.signIn() ### Description Sends an OTP to an existing user for sign in. ### Method Signature ```dart Future signIn({ required DeliveryMethod method, required String loginId, SignInOptions? options, }) ``` ### Parameters #### Path Parameters - **method** (DeliveryMethod) - Required - `DeliveryMethod.email`, `DeliveryMethod.sms`, or `DeliveryMethod.whatsapp` - **loginId** (String) - Required - Email, phone number, or username - **options** (SignInOptions?) - Optional - Step-up, MFA, custom claims, or session revocation options ### Returns Future — Masked email/phone ### Throws DescopeException ### Example ```dart await Descope.otp.signIn( method: DeliveryMethod.sms, loginId: '+1234567890', ); ``` ``` -------------------------------- ### Password Get Policy Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/authentication-methods.md Fetches the current password policy configuration from the Descope console. This allows clients to inform users about password requirements. ```APIDOC ## getPolicy() ### Description Fetches the password policy configured in the console. ### Method Future ### Response #### Success Response - **PasswordPolicy** - Contains password policy requirements like minLength, lowercase, uppercase, number, nonAlphanumeric. ### Throws - DescopeException ### Example ```dart final policy = await Descope.password.getPolicy(); print('Min length: ${policy.minLength}'); print('Requires uppercase: ${policy.uppercase}'); ``` ``` -------------------------------- ### signUp (TOTP) Source: https://github.com/descope/descope-flutter/blob/main/_autodocs/api-reference/authentication-methods.md Creates a new user and generates a TOTP seed for time-based one-time password authentication. Requires a login ID and optional sign-up details. ```APIDOC ## signUp() (TOTP) ### Description Creates a new user and generates a TOTP seed. ### Method Signature ```dart Future signUp({ required String loginId, SignUpDetails? details, }) ``` ### Parameters #### Path Parameters - **loginId** (String) - Required - Unique identifier (email, username, etc.) - **details** (SignUpDetails?) - Optional - Additional user information ### Returns Future with provisioning URL, QR code image, and seed key ### Throws DescopeException ### Example ```dart final totpResponse = await Descope.totp.signUp( loginId: 'user@example.com', details: SignUpDetails(name: 'John Doe'), ); // Display QR code to user Image.memory(totpResponse.image) // Or show the key manually print('Seed: ${totpResponse.key}'); print('Provisioning URL: ${totpResponse.provisioningUrl}'); ``` ```