auth0_flutter 1.0.1 copy "auth0_flutter: ^1.0.1" to clipboard
auth0_flutter: ^1.0.1 copied to clipboard

Auth0 SDK for Flutter. Easily integrate Auth0 into Android / iOS Flutter apps.

Auth0 SDK for Flutter #

CircleCI Codecov Package

Auth0 SDK for Android / iOS Flutter apps.


Table of Contents #

Features #

  • Web Auth
    • Login
    • Logout
    • Automatic storage and renewal of user's credentials
  • Authentication API
    • Login with username or email and password
    • Signup
    • Get user information from /userinfo
    • Renew user's credentials
    • Reset password
  • Credentials manager
  • Support for custom credentials manager implementations

Documentation #

  • Quickstart
    Shows how to integrate auth0_flutter into an Android / iOS Flutter app from scratch.
  • Sample app
    A complete, running Android / iOS Flutter app you can try.
  • API documentation
    Documentation auto-generated from the code comments that explains all the available features.
  • FAQ
    Answers some common questions about flutter_auth0.

Requirements #

Flutter Android iOS
SDK 3.0+ Android API 21+ iOS 12+
Dart 2.17+ Java 8+ Swift 5.3+
Xcode 13.x / 14.x

Installation #

Add auth0_flutter into your project:

flutter pub add auth0_flutter

Getting Started #

Configuration #

auth0_flutter needs the client ID and domain of the Auth0 application to communicate with Auth0. You can find these details on the settings page of your Auth0 application. If you are using a custom domain, use the value of your custom domain instead of the value from the settings page.

⚠️ Make sure that the application type of the Auth0 application is Native, and has the Token Endpoint Authentication Method set to None. If you don’t have a Native Auth0 application already, create one before continuing.

final auth0 = Auth0('YOUR_AUTH0_DOMAIN', 'YOUR_AUTH0_CLIENT_ID');

Web Auth Configuration #

Configure callback and logout URLs

The callback and logout URLs are the URLs that Auth0 invokes to redirect back to your app. Auth0 invokes the callback URL after authenticating the user, and the logout URL after removing the session cookie.

Since callback and logout URLs can be manipulated, you will need to add your URLs to the Allowed Callback URLs and Allowed Logout URLs fields in the settings page of your Auth0 application. This will enable Auth0 to recognize these URLs as valid. If the callback and logout URLs are not set, users will be unable to log in and out of the app and will get an error.

Go to the settings page of your Auth0 application and add the corresponding URLs to Allowed Callback URLs and Allowed Logout URLs, according to the platforms used by your app. If you are using a custom domain, replace YOUR_AUTH0_DOMAIN with the value of your custom domain instead of the value from the settings page.

Android
https://YOUR_AUTH0_DOMAIN/android/YOUR_APP_PACKAGE_NAME/callback

For example, if your Auth0 domain was company.us.auth0.com and your Android app package name was com.company.myapp, then this value would be:

https://company.us.auth0.com/android/com.company.myapp/callback
iOS
YOUR_BUNDLE_IDENTIFIER://YOUR_AUTH0_DOMAIN/ios/YOUR_BUNDLE_IDENTIFIER/callback

For example, if your iOS bundle identifier was com.company.myapp and your Auth0 domain was company.us.auth0.com, then this value would be:

com.company.myapp://company.us.auth0.com/ios/com.company.myapp/callback

Android configuration: manifest placeholders

Open the android/build.gradle file and add the following manifest placeholders inside android > defaultConfig.

// android/build.gradle

android {
    // ...

    defaultConfig {
        // ...
        // Add the following line
        manifestPlaceholders = [auth0Domain: "YOUR_AUTH0_DOMAIN", auth0Scheme: "https"]
    }

    // ...
}

For example, if your Auth0 domain was company.us.auth0.com, then the manifest placeholders line would be:

manifestPlaceholders = [auth0Domain: "company.us.auth0.com", auth0Scheme: "https"]

💡 If your Android app is using product flavors, you might need to specify different manifest placeholders for each flavor.

Skipping the Android Web Auth configuration

If you don't plan to use Web Auth, you will notice that the compiler will still prompt you to provide the manifestPlaceholders values, since the RedirectActivity included in this library will require them, and the Gradle tasks won't be able to run without them.

Re-declare the activity manually using tools:node="remove" in the android/src/main/AndroidManifest.xml file to make the manifest merger remove it from the final manifest file. Additionally, one more unused activity can be removed from the final APK by using the same process. A complete snippet to achieve this is:

<!-- android/src/main/AndroidManifest.xml -->

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.company.myapp">
    <application android:theme="@style/AppTheme">
        <!-- ... -->

        <activity
            android:name="com.auth0.android.provider.AuthenticationActivity"
            tools:node="remove"/>
        <!-- Optional: Remove RedirectActivity -->
        <activity
            android:name="com.auth0.android.provider.RedirectActivity"
            tools:node="remove"/>

        <!-- ... -->
    </application>
</manifest>

iOS configuration: custom URL scheme

Open the ios/Runner/Info.plist file and add the following snippet inside the top-level <dict> tag. This registers your iOS bundle identifier as a custom URL scheme, so the callback and logout URLs can reach your app.

<!-- ios/Runner/Info.plist -->

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<!-- ... -->

    <key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeRole</key>
            <string>None</string>
            <key>CFBundleURLName</key>
            <string>auth0</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
            </array>
        </dict>
    </array>

<!-- ... -->
</dict>
</plist>

💡 If you're opening the Info.plist file in Xcode and it is not being shown in this format, you can Right Click on Info.plist in the Xcode project navigator and then select Open As > Source Code.

Web Auth Login #

Import auth0_flutter in the file where you want to present the login page.

import 'package:auth0_flutter/auth0_flutter.dart';

Then, present the Universal Login page in the onPressed callback of your Login button.

final credentials = await auth0.webAuthentication().login();
// Access token -> credentials.accessToken
// User profile -> credentials.user

auth0_flutter will automatically store the user's credentials using the built-in Credentials Manager instance. You can access this instance through the credentialsManager property.

final credentials = await auth0.credentialsManager.credentials();
Add an audience value

Specify an audience to obtain an access token that can be used to make authenticated requests to a backend. The audience value is the API Identifier of your Auth0 API, for example https://example.com/api.

final credentials = await auth0
    .webAuthentication()
    .login(audience: 'YOUR_AUTH0_API_IDENTIFIER');
Add scope values

Specify scopes to request permission to access protected resources, like the user profile. The default scope values are openid, profile, email, and offline_access. Regardless of the values specified, openid is always included.

final credentials = await auth0
    .webAuthentication()
    .login(scopes: {'profile', 'email', 'offline_access', 'read:todos'});
Add custom parameters

Specify additional parameters by passing a parameters map.

final credentials = await auth0
    .webAuthentication()
    .login(parameters: {'connection': 'github'});

Web Auth Logout #

Logging the user out involves clearing the Universal Login session cookie and then deleting the user's credentials from your app.

Call the logout() method in the onPressed callback of your Logout button. Once the session cookie has been cleared, auth0_flutter will automatically delete the user's credentials. If you're using your own credentials storage, make sure to delete the credentials afterward.

await auth0.webAuthentication().logout();

Custom Scheme (Android) #

On Android, https is used by default as the callback URL scheme. This works best for Android API 23+ if you're using Android App Links, but in previous Android versions, this may show the intent chooser dialog prompting the user to choose either your app or the browser. You can change this behavior by using a custom unique scheme so that Android opens the link directly with your app.

  1. Update the auth0Scheme manifest placeholder on the android/build.gradle file.
  2. Update the Allowed Callback URLs in the settings page of your Auth0 application.
  3. Pass the scheme value to the webAuthentication() method.
final webAuth = auth0.webAuthentication(scheme: 'YOUR_CUSTOM_SCHEME');

// Login
final credentials = await webAuth.login();
// Logout
await webAuth.logout();

💡 Note that custom schemes can only have lowercase letters.

SSO Alert Box (iOS) #

ios-sso-alert

Check the FAQ for more information about the alert box that pops up by default when using Web Auth on iOS.

💡 See also this blog post for a detailed overview of Single Sign-On (SSO) on iOS.

Go up ⤴

Common Tasks #

Web Auth #

Web Auth signup

You can make users land directly on the Signup page instead of the Login page by specifying the 'screen_hint': 'signup' parameter. Note that this can be combined with 'prompt': 'login', which indicates whether you want to always show the authentication page or you want to skip if there's an existing session.

Parameters No existing session Existing session
No extra parameters Shows the login page Redirects to the callback URL
'screen_hint': 'signup' Shows the signup page Redirects to the callback URL
'prompt': 'login' Shows the login page Shows the login page
'prompt': 'login', 'screen_hint': 'signup' Shows the signup page Shows the signup page
final credentials = await auth0
    .webAuthentication()
    .login(parameters: {'screen_hint': 'signup'});

⚠️ The screen_hint parameter will work with the New Universal Login Experience without any further configuration. If you are using the Classic Universal Login Experience, you need to customize the login template to look for this parameter and set the initialScreen option of the Auth0Lock constructor.

ID token validation

auth0_flutter automatically validates the ID token obtained from Web Auth login, following the OpenID Connect specification. This ensures the contents of the ID token have not been tampered with and can be safely used.

You can configure the ID token validation by passing an IdTokenValidationConfig instance. Check the API documentation to learn more about the available configuration options.

const config = IdTokenValidationConfig(leeway: 10);
final credentials =
    await auth0.webAuthentication().login(idTokenValidationConfig: config);
Custom domains

Users of Auth0 Private Cloud with custom domains still on the legacy behavior need to specify a custom issuer to match the Auth0 domain when performing Web Auth login. Otherwise, the ID token validation will fail.

const config =
    IdTokenValidationConfig(issuer: 'https://YOUR_AUTH0_DOMAIN/');
final credentials =
    await auth0.webAuthentication().login(idTokenValidationConfig: config);

Disable credentials storage

By default, auth0_flutter will automatically store the user's credentials after login and delete them after logout, using the built-in Credentials Manager instance. If you prefer to use your own credentials storage, you need to disable the built-in Credentials Manager.

final credentials =
    await auth0.webAuthentication(useCredentialsManager: false).login();

Web Auth errors

Web Auth will only throw WebAuthenticationException exceptions. Check the API documentation to learn more about the available WebAuthenticationException properties.

try {
  final credentials = await auth0.webAuthentication().login();
  // ...
} on WebAuthenticationException catch (e) {
  print(e);
}

Credentials Manager #

The Credentials Manager utility allows you to securely store and retrieve the user's credentials. The credentials will be stored encrypted in Shared Preferences on Android, and in the Keychain on iOS.

💡 If you're using Web Auth, you do not need to manually store the credentials after login and delete them after logout; auth0_flutter does it automatically.

Check for stored credentials

When the users open your app, check for valid credentials. If they exist, you can retrieve them and redirect the users to the app's main flow without any additional login steps.

final isLoggedIn = await auth0.credentialsManager.hasValidCredentials();

if (isLoggedIn) {
  // Retrieve the credentials and redirect to the main flow
} else {
  // No valid credentials exist, present the login page
}

Retrieve stored credentials

The credentials will be automatically renewed (if expired) using the refresh token. This method is thread-safe.

final credentials = await auth0.credentialsManager.credentials();

💡 You do not need to call credentialsManager.storeCredentials() afterward. The Credentials Manager automatically persists the renewed credentials.

Custom implementations

flutter_auth0 exposes a built-in, default Credentials Manager implementation through the credentialsManager property. You can pass your own implementation to the Auth0 constructor. If you're using Web Auth, this implementation will be used to store the user's credentials after login and delete them after logout.

final customCredentialsManager = CustomCredentialsManager();
final auth0 = Auth0('YOUR_AUTH0_DOMAIN', 'YOUR_AUTH0_CLIENT_ID',
    credentialsManager: customCredentialsManager);
// auth0.credentialsManager is now your CustomCredentialsManager instance

Local authentication

You can enable an additional level of user authentication before retrieving credentials using the local authentication supported by the device, for example PIN or fingerprint on Android, and Face ID or Touch ID on iOS.

const localAuthentication =
    LocalAuthentication(title: 'Please authenticate to continue');
final auth0 = Auth0('YOUR_AUTH0_DOMAIN', 'YOUR_AUTH0_CLIENT_ID',
    localAuthentication: localAuthentication);
final credentials = await auth0.credentialsManager.credentials();

Check the API documentation to learn more about the available LocalAuthentication properties.

⚠️ Enabling local authentication will not work if you're using a custom Credentials Manager implementation. In that case, you will need to build support for local authentication into your custom implementation.

Credentials Manager errors

The Credentials Manager will only throw CredentialsManagerException exceptions. You can find more information in the details property of the exception. Check the API documentation to learn more about the available CredentialsManagerException properties.

try {
  final credentials = await auth0.credentialsManager.credentials();
  // ...
} on CredentialsManagerException catch (e) {
  print(e);
}

API #

The Authentication API exposes the AuthN/AuthZ functionality of Auth0, as well as the supported identity protocols like OpenID Connect, OAuth 2.0, and SAML. We recommend using Universal Login, but if you prefer to build your own UI you can use our API endpoints to do so. However, some Auth flows (grant types) are disabled by default so you must enable them on the settings page of your Auth0 application, as explained in Update Grant Types.

To log in or sign up with a username and password, the Password grant type needs to be enabled in your app. If you set the grants via the Management API you should activate both http://auth0.com/oauth/grant-type/password-realm and Password. Otherwise, the Auth0 Dashboard will take care of activating both when enabling Password.

💡 If your Auth0 account has the Bot Detection feature enabled, your requests might be flagged for verification. Check how to handle this scenario in the Bot Detection section.

⚠️ The ID tokens obtained from Web Auth login are automatically validated by auth0_flutter, ensuring their contents have not been tampered with. This is not the case for the ID tokens obtained from the Authentication API client. You must validate any ID tokens received from the Authentication API client before using the information they contain.

Login with database connection

final credentials = await auth0.api.login(
    usernameOrEmail: 'jane.smith@example.com',
    password: 'secret-password',
    connectionOrRealm: 'Username-Password-Authentication');

// Store the credentials afterward
final didStore =
    await auth0.credentialsManager.storeCredentials(credentials);
Add an audience value

Specify an audience to obtain an access token that can be used to make authenticated requests to a backend. The audience value is the API Identifier of your Auth0 API, for example https://example.com/api.

final credentials = await auth0.api.login(
    usernameOrEmail: 'jane.smith@example.com',
    password: 'secret-password',
    connectionOrRealm: 'Username-Password-Authentication',
    audience: 'YOUR_AUTH0_API_IDENTIFIER');
Add scope values

Specify scopes to request permission to access protected resources, like the user profile. The default scope values are openid, profile, email, and offline_access. Regardless of the values specified, openid is always included.

final credentials = await auth0.api.login(
    usernameOrEmail: 'jane.smith@example.com',
    password: 'secret-password',
    connectionOrRealm: 'Username-Password-Authentication',
    scopes: {'profile', 'email', 'offline_access', 'read:todos'});

Sign up with database connection

final databaseUser = await auth0.api.signup(
    email: 'jane.smith@example.com',
    password: 'secret-password',
    connection: 'Username-Password-Authentication',
    userMetadata: {'first_name': 'Jane', 'last_name': 'Smith'});

💡 You might want to log the user in after signup. See Login with database connection above for an example.

Retrieve user information

Fetch the latest user information from the /userinfo endpoint.

This method will yield a UserProfile instance. Check the API documentation to learn more about its available properties.

final userProfile = await auth0.api.userInfo(accessToken: accessToken);

Renew credentials

Use a refresh token to renew the user's credentials. It's recommended that you read and understand the refresh token process beforehand.

final newCredentials =
    await auth0.api.renewCredentials(refreshToken: refreshToken);

// Store the credentials afterward
final didStore =
    await auth0.credentialsManager.storeCredentials(newCredentials);

💡 To obtain a refresh token, make sure your Auth0 application has the refresh token grant enabled. If you are also specifying an audience value, make sure that the corresponding Auth0 API has the Allow Offline Access setting enabled.

API client errors

The Authentication API client will only throw ApiException exceptions. You can find more information in the details property of the exception. Check the API documentation to learn more about the available ApiException properties.

try {
  final credentials = await auth0.api.login(
      usernameOrEmail: email,
      password: password,
      connectionOrRealm: connection);
  // ...
} on ApiException catch (e) {
  print(e);
}

Go up ⤴

Advanced Features #

Organizations #

Organizations is a set of features that provide better support for developers who build and maintain SaaS and Business-to-Business (B2B) applications.

💡 Organizations is currently only available to customers on our Enterprise and Startup subscription plans.

Log in to an organization

final credentials = await auth0
    .webAuthentication()
    .login(organizationId: 'YOUR_AUTH0_ORGANIZATION_ID');

Accept user invitations

To accept organization invitations your app needs to support deep linking, as invitation links are HTTPS-only. Tapping on the invitation link should open your app.

When your app gets opened by an invitation link, grab the invitation URL and pass it to the login() method.

final credentials =
    await auth0.webAuthentication().login(invitationUrl: url);

Bot Detection #

If you are performing database login/signup via the Authentication API and would like to use the Bot Detection feature, you need to handle the isVerificationRequired error. It indicates that the request was flagged as suspicious and an additional verification step is necessary to log the user in. That verification step is web-based, so you need to use Web Auth to complete it.

try {
  final credentials = await auth0.api.login(
      usernameOrEmail: email,
      password: password,
      connectionOrRealm: connection,
      scopes: scopes);
  // ...
} on ApiException catch (e) {
  if (e.isVerificationRequired) {
    final credentials = await auth0.webAuthentication().login(
        scopes: scopes,
        useEphemeralSession: true, // Otherwise a session cookie will remain (iOS-only)
        parameters: {
          'connection': connection,
          'login_hint': email // So the user doesn't have to type it again
        });
    // ...
  }
}

Issue Reporting #

For general support or usage questions, use the Auth0 Community forums or raise a support ticket. Only raise an issue if you have found a bug or want to request a feature.

Do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.

What is Auth0? #

Auth0 helps you to:

  • Add authentication with multiple sources, either social identity providers such as Google, Facebook, Microsoft Account, LinkedIn, GitHub, Twitter, Box, Salesforce (amongst others), or enterprise identity systems like Windows Azure AD, Google Apps, Active Directory, ADFS, or any SAML identity provider.
  • Add authentication through more traditional username/password databases.
  • Add support for linking different user accounts with the same user.
  • Support for generating signed JSON web tokens to call your APIs and flow the user identity securely.
  • Analytics of how, when, and where users are logging in.
  • Pull data from other sources and add it to the user profile through JavaScript Actions.

Why Auth0? Because you should save time, be happy, and focus on what really matters: building your product.

License #

This project is licensed under Apache License 2.0. See the LICENSE file for more information.


Go up ⤴

54
likes
0
pub points
96%
popularity

Publisher

verified publisherauth0.com

Auth0 SDK for Flutter. Easily integrate Auth0 into Android / iOS Flutter apps.

Repository (GitHub)
View/report issues

License

unknown (LICENSE)

Dependencies

auth0_flutter_platform_interface, flutter

More

Packages that depend on auth0_flutter