Add authentication to your Flutter application
This tutorial will show you how to integrate Logto into your Flutter application.
- The SDK package is available on pub.dev and Logto GitHub repository.
- The sample project is built using Flutter material. You can find it on pub.dev.
- This SDK is compatible with Flutter applications on iOS, Android, and Web platforms. Compatibility with other platforms has not been tested.
Prerequisites
- A Logto Cloud account or a self-hosted Logto.
- A Logto native application created.
- A Flutter or Dart development environment.
Installation
- pub.dev
- GitHub
You can install the logto_dart_sdk package
directly using the pub package manager.
Run the following command under your project root:
flutter pub add logto_dart_sdk
Or add the following to your pubspec.yaml
file:
dependencies:
logto_dart_sdk: ^3.0.0
Then run:
flutter pub get
If you prefer to fork your own version of the SDK, you can clone the repository directly from GitHub.
git clone https://github.com/logto-io/dart
Set up
SDK version compatibility
Logto SDK version | Dart SDK version | Dart 3.0 compatible |
---|---|---|
< 2.0.0 | >= 2.17.6 < 3.0.0 | false |
>= 2.0.0 < 3.0.0 | >= 3.0.0 | true |
>= 3.0.0 | >= 3.6.0 | true |
flutter_secure_storage set up
Under the hood, this SDK uses flutter_secure_storage to implement the cross-platform persistent secure token storage.
- Keychain is used for iOS
- AES encryption is used for Android.
Config Android version
Set the android:minSdkVersion to >= 18
in your project's android/app/build.gradle
file.
android {
...
defaultConfig {
...
minSdkVersion 18
...
}
}
Disable auto backup on Android
By default Android backups data on Google Drive. It can cause exception java.security.InvalidKeyException:Failed
to unwrap key. To avoid this,
-
To disable auto backup, go to your app manifest file and set the
android:allowBackup
andandroid:fullBackupContent
attributes tofalse
.AndroidManifest.xml<manifest ... >
...
<application
android:allowBackup="false"
android:fullBackupContent="false"
...
>
...
</application>
</manifest> -
Exclude
sharedprefs
fromFlutterSecureStorage
.If you need to keep the
android:fullBackupContent
for your app rather than disabling it, you can exclude thesharedprefs
directory from the backup. See more details in the Android documentation.In your AndroidManifest.xml file, add the android:fullBackupContent attribute to the
<application>
element, as shown in the following example. This attribute points to an XML file that contains backup rules.AndroidManifest.xml<application ...
android:fullBackupContent="@xml/backup_rules">
</application>Create an XML file called
@xml/backup_rules
in theres/xml/
directory. In this file, add rules with the<include>
and<exclude>
elements. The following sample backs up all shared preferences except device.xml:@xml/backup_rules<?xml version="1.0" encoding="utf-8"?>
<full-backup-content>
<exclude domain="sharedpref" path="FlutterSecureStorage"/>
</full-backup-content>
Please check flutter_secure_storage for more details.
flutter_web_auth_2 set up
Behind the scenes, this SDK uses flutter_web_auth_2 to authenticate users with Logto. This package provides a simple way to authenticate users with Logto using the system webview or browser.
This plugin uses ASWebAuthenticationSession
on iOS 12+ and macOS 10.15+, SFAuthenticationSession
on iOS 11, Chrome Custom Tabs
on Android and opens a new window on Web.
-
iOS: No additional setup required
-
Android: Register the callback url on Android
In order to capture the callback url from Logto's sign-in web page, you will need to register your sign-in redirectUri to your
AndroidManifest.xml
file.AndroidManifest.xml<manifest>
<application>
<activity
android:name="com.linusu.flutter_web_auth_2.CallbackActivity"
android:exported="true">
<intent-filter android:label="flutter_web_auth_2">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="YOUR_CALLBACK_URL_SCHEME_HERE" />
</intent-filter>
</activity>
</application>
</manifest> -
Web browser: Create an endpoint to handle the callback URL
If you are using the web platform, you need to create an endpoint to handle the callback URL and send it back to the application using the
postMessage
API.callback.html<!doctype html>
<title>Authentication complete</title>
<p>Authentication is complete. If this does not happen automatically, please close the window.</p>
<script>
function postAuthenticationMessage() {
const message = {
'flutter-web-auth-2': window.location.href,
};
if (window.opener) {
window.opener.postMessage(message, window.location.origin);
window.close();
} else if (window.parent && window.parent !== window) {
window.parent.postMessage(message, window.location.origin);
} else {
localStorage.setItem('flutter-web-auth-2', window.location.href);
window.close();
}
}
postAuthenticationMessage();
</script>
Please check the setup guide in the flutter_web_auth_2 package for more details.
Integration
Init LogtoClient
Import the logto_dart_sdk
package and initialize the LogtoClient
instance at the root of your application.
import 'package:logto_dart_sdk/logto_dart_sdk.dart';
import 'package:http/http.dart' as http;
void main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Flutter Demo',
home: MyHomePage(title: 'Logto Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late LogtoClient logtoClient;
void render() {
// state change
}
// LogtoConfig
final logtoConfig = const LogtoConfig(
endpoint: "<your-logto-endpoint>",
appId: "<your-app-id>"
);
void _init() {
logtoClient = LogtoClient(
config: logtoConfig,
httpClient: http.Client(), // Optional http client
);
render();
}
void initState() {
super.initState();
_init();
}
// ...
}
Implement sign-in
Before we dive into the details, here's a quick overview of the end-user experience. The sign-in process can be simplified as follows:
- Your app invokes the sign-in method.
- The user is redirected to the Logto sign-in page. For native apps, the system browser is opened.
- The user signs in and is redirected back to your app (configured as the redirect URI).
Regarding redirect-based sign-in
- This authentication process follows the OpenID Connect (OIDC) protocol, and Logto enforces strict security measures to protect user sign-in.
- If you have multiple apps, you can use the same identity provider (Logto). Once the user signs in to one app, Logto will automatically complete the sign-in process when the user accesses another app.
To learn more about the rationale and benefits of redirect-based sign-in, see Logto sign-in experience explained.
Before starting, you need to add a redirect URI in the Admin Console for your application.
Let's switch to the Application details page of Logto Console. Add a Redirect URI io.logto://callback
and click "Save changes".

- For iOS, the redirect URI scheme does not really matter since the
ASWebAuthenticationSession
class will listen to the redirect URI regardless of if it's registered. - For Android, the redirect URI scheme must be registered in the
AndroidManifest.xml
file.
After the redirect URI is configured, we add a sign-in button to your page, which will call logtoClient.signIn
API to invoke the Logto sign-in flow:
class _MyHomePageState extends State<MyHomePage> {
// ...
final redirectUri = 'io.logto://callback';
Widget build(BuildContext context) {
// ...
Widget signInButton = TextButton(
onPressed: () async {
await logtoClient.signIn(redirectUri);
render();
},
child: const Text('Sign In'),
);
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SelectableText('My Demo App'),
signInButton,
],
),
),
);
}
}
Implement sign-out
Let's switch to the Application details page of Logto Console. Add a Post Sign-out Redirect
URI io.logto://callback
and click "Save changes".

Post Sign-outRedirect URI is an OAuth 2.0 concept which implies the location should redirect after signing out.
Now let's add a sign-out button on the main page so users can sign out from your application.
class _MyHomePageState extends State<MyHomePage> {
// ...
final postSignOutRedirectUri = 'io.logto//home';
Widget build(BuildContext context) {
// ...
Widget signOutButton = TextButton(
onPressed: () async {
await logtoClient.signOut(postSignOutRedirectUri);
render();
},
child: const Text('Sign Out'),
);
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SelectableText('My Demo App'),
signInButton,
signOutButton,
],
),
),
);
}
}
Handle authentication status
Logto SDK provides an asynchronous method to check the authentication status. The method is logtoClient.isAuthenticated
. The method returns a boolean value, true
if the user is authenticated, otherwise false
.
In the example we conditionally render the sign-in and sign-out buttons based on the authentication status. Now let's update the render
method in our Widget to handle the state change:
class _MyHomePageState extends State<MyHomePage> {
// ...
bool? isAuthenticated = false;
void render() {
setState(() async {
isAuthenticated = await logtoClient.isAuthenticated;
});
}
Widget build(BuildContext context) {
// ...
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SelectableText('My Demo App'),
isAuthenticated == true ? signOutButton : signInButton,
],
),
),
);
}
}
Checkpoint: Test your application
Now, you can test your application:
- Run your application, you will see the sign-in button.
- Click the sign-in button, the SDK will init the sign-in process and redirect you to the Logto sign-in page.
- After you signed in, you will be redirected back to your application and see the sign-out button.
- Click the sign-out button to clear token storage and sign out.
Get user information
Display user information
To display the user's information, you can use the logtoClient.idTokenClaims
getter. For example, in a Flutter app:
class _MyHomePageState extends State<MyHomePage> {
// ...
Widget build(BuildContext context) {
// ...
Widget getUserInfoButton = TextButton(
onPressed: () async {
final userClaims = await logtoClient.idTokenClaims;
print(userInfo);
},
child: const Text('Get user info'),
);
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SelectableText('My Demo App'),
isAuthenticated == true ? signOutButton : signInButton,
isAuthenticated == true ? getUserInfoButton : const SizedBox.shrink(),
],
),
),
);
}
}
Request additional claims
You may find some user information are missing in the returned object from client.idTokenClaims
. This is because OAuth 2.0 and OpenID Connect (OIDC) are designed to follow the principle of least privilege (PoLP), and Logto is built on top of these standards.
By default, limited claims are returned. If you need more information, you can request additional scopes to access more claims.
A "claim" is an assertion made about a subject; a "scope" is a group of claims. In the current case, a claim is a piece of information about the user.
Here's a non-normative example the scope - claim relationship:
The "sub" claim means "subject", which is the unique identifier of the user (i.e. user ID).
Logto SDK will always request three scopes: openid
, profile
, and offline_access
.
To request additional scopes, you can pass the scopes to the LogtoConfig
object. For example:
// LogtoConfig
final logtoConfig = const LogtoConfig(
endpoint: "<your-logto-endpoint>",
appId: "<your-app-id>",
scopes: ["email", "phone"],
);
We also provide a built-in LogtoUserScope
enum is the SDK package to help you use the predefined scopes.
// LogtoConfig
final logtoConfig = const LogtoConfig(
endpoint: "<your-logto-endpoint>",
appId: "<your-app-id>",
scopes: [LogtoUserScope.email.value, LogtoUserScope.phone.value],
);
Claims that need network requests
To prevent bloating the ID token, some claims require network requests to fetch. For example, the custom_data
claim is not included in the user object even if it's requested in the scopes. To access these claims, you can use the logtoClient.getUserInfo()
method:
class _MyHomePageState extends State<MyHomePage> {
// ...
Widget build(BuildContext context) {
// ...
Widget getUserInfoButton = TextButton(
onPressed: () async {
final userInfo = await logtoClient.getUserInfo();
print(userInfo);
},
child: const Text('Get user info'),
);
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SelectableText('My Demo App'),
isAuthenticated == true ? signOutButton : signInButton,
isAuthenticated == true ? getUserInfoButton : const SizedBox.shrink(),
],
),
),
);
}
}
Scopes and claims
Logto uses OIDC scopes and claims conventions to define the scopes and claims for retrieving user information from the ID token and OIDC userinfo endpoint. Both of the "scope" and the "claim" are terms from the OAuth 2.0 and OpenID Connect (OIDC) specifications.
Here's the list of supported scopes and the corresponding claims:
openid
Claim name | Type | Description | Needs userinfo? |
---|---|---|---|
sub | string | The unique identifier of the user | No |
profile
Claim name | Type | Description | Needs userinfo? |
---|---|---|---|
name | string | The full name of the user | No |
username | string | The username of the user | No |
picture | string | URL of the End-User's profile picture. This URL MUST refer to an image file (for example, a PNG, JPEG, or GIF image file), rather than to a Web page containing an image. Note that this URL SHOULD specifically reference a profile photo of the End-User suitable for displaying when describing the End-User, rather than an arbitrary photo taken by the End-User. | No |
created_at | number | Time the End-User was created. The time is represented as the number of milliseconds since the Unix epoch (1970-01-01T00:00:00Z). | No |
updated_at | number | Time the End-User's information was last updated. The time is represented as the number of milliseconds since the Unix epoch (1970-01-01T00:00:00Z). | No |
Other standard claims include family_name
, given_name
, middle_name
, nickname
, preferred_username
, profile
, website
, gender
, birthdate
, zoneinfo
, and locale
will be also included in the profile
scope without the need for requesting the userinfo endpoint. A difference compared to the claims above is that these claims will only be returned when their values are not empty, while the claims above will return null
if the values are empty.
Unlike the standard claims, the created_at
and updated_at
claims are using milliseconds instead of seconds.
email
Claim name | Type | Description | Needs userinfo? |
---|---|---|---|
string | The email address of the user | No | |
email_verified | boolean | Whether the email address has been verified | No |
phone
Claim name | Type | Description | Needs userinfo? |
---|---|---|---|
phone_number | string | The phone number of the user | No |
phone_number_verified | boolean | Whether the phone number has been verified | No |
address
Please refer to the OpenID Connect Core 1.0 for the details of the address claim.
custom_data
Claim name | Type | Description | Needs userinfo? |
---|---|---|---|
custom_data | object | The custom data of the user | Yes |
identities
Claim name | Type | Description | Needs userinfo? |
---|---|---|---|
identities | object | The linked identities of the user | Yes |
sso_identities | array | The linked SSO identities of the user | Yes |
roles
Claim name | Type | Description | Needs userinfo? |
---|---|---|---|
roles | string[] | The roles of the user | No |
urn:logto:scope:organizations
Claim name | Type | Description | Needs userinfo? |
---|---|---|---|
organizations | string[] | The organization IDs the user belongs to | No |
organization_data | object[] | The organization data the user belongs to | Yes |
urn:logto:scope:organization_roles
Claim name | Type | Description | Needs userinfo? |
---|---|---|---|
organization_roles | string[] | The organization roles the user belongs to with the format of <organization_id>:<role_name> | No |
Considering performance and the data size, if "Needs userinfo?" is "Yes", it means the claim will not show up in the ID token, but will be returned in the userinfo endpoint response.
API resources and organizations
We recommend to read 🔐 Role-Based Access Control (RBAC) first to understand the basic concepts of Logto RBAC and how to set up API resources properly.
Configure Logto client
Once you have set up the API resources, you can add them when configuring Logto in your app:
// LogtoConfig
final logtoConfig = const LogtoConfig(
endpoint: "<your-logto-endpoint>",
appId: "<your-app-id>",
// Add your API resources
resources: ["https://shopping.your-app.com/api", "https://store.your-app.com/api"],
);
Each API resource has its own permissions (scopes).
For example, the https://shopping.your-app.com/api
resource has the shopping:read
and shopping:write
permissions, and the https://store.your-app.com/api
resource has the store:read
and store:write
permissions.
To request these permissions, you can add them when configuring Logto in your app:
// LogtoConfig
final logtoConfig = const LogtoConfig(
endpoint: "<your-logto-endpoint>",
appId: "<your-app-id>",
resources: ["https://shopping.your-app.com/api", "https://store.your-app.com/api"],
// Add your API resources' scopes
scopes: ["shopping:read", "shopping:write", "store:read", "store:write"]
);
You may notice that scopes are defined separately from API resources. This is because Resource Indicators for OAuth 2.0 specifies the final scopes for the request will be the cartesian product of all the scopes at all the target services.
Thus, in the above case, scopes can be simplified from the definition in Logto, both of the API resources can have read
and write
scopes without the prefix. Then, in the Logto config:
// LogtoConfig
final logtoConfig = const LogtoConfig(
endpoint: "<your-logto-endpoint>",
appId: "<your-app-id>",
resources: ["https://shopping.your-app.com/api", "https://store.your-app.com/api"],
// Shared scopes by all resources
scopes: ["read", "write"]
);
For every API resource, it will request for both read
and write
scopes.
It is fine to request scopes that are not defined in the API resources. For example, you can request the email
scope even if the API resources don't have the email
scope available. Unavailable scopes will be safely ignored.
After the successful sign-in, Logto will issue proper scopes to API resources according to the user's roles.
Fetch access token for the API resource
To fetch the access token for a specific API resource, you can use the getAccessToken
method:
Future<AccessToken?> getAccessToken(String resource) async {
var token = await logtoClient.getAccessToken(resource: resource);
return token;
}
This method will return a JWT access token that can be used to access the API resource when the user has related permissions. If the current cached access token has expired, this method will automatically try to use a refresh token to get a new access token.
Fetch access token for organizations
Just like API resources, you may also request for a access token for organizations. This is useful when you need to access resources that are defined using the organization scope instead of the API resource scope.
If organization is new to you, please read 🏢 Organizations (Multi-tenancy) to get started.
You need to add LogtoUserScope.Organizations
scope when configuring the Logto client:
// LogtoConfig
final logtoConfig = const LogtoConfig(
endpoint: "<your-logto-endpoint>",
appId: "<your-app-id>",
scopes: [LogtoUserScopes.organizations.value]
);
Once the user is signed in, you can fetch the organization token for the user:
// Valid organization IDs for the user can be found in the ID token claim `organizations`.
Future<AccessToken?> getOrganizationAccessToken(String organizationId) async {
var token = await logtoClient.getOrganizationToken(organizationId);
return token;
}
Migration guide
If you are migration from a previous version of Logto Dart SDK, version < 3.0.0:
-
Update your
pubspec.yaml
file to use the latest version of the Logto Dart SDK.pubspec.yamldependencies:
logto_dart_sdk: ^3.0.0 -
Update the Android manifest file, replace the legacy
flutter_web_auth
callback activity with the newflutter_web_auth_2
.FlutterWebAuth
->FlutterWebAuth2
flutter_web_auth
->flutter_web_auth_2
-
Pass the
redirectUri
to thesignOut
method.redirectUri
is now required when calling thesignOut
method. For iOS platform, this parameter is useless, but for Android and Web platforms which require an additionalend_session
request to clean up the sign-in session, this parameter will be used as thepost_logout_redirect_uri
parameter in theend_session
request.await logtoClient.signOut(redirectUri);
Troubleshooting
Troubleshooting Android
-
You will need to update your AndroidManifest.xml to include the
com.linusu.flutter_web_auth_2.CallbackActivity
activity, something like:android/app/src/main/AndroidManifest.xml<manifest>
<application>
<!-- add the com.linusu.flutter_web_auth_2.CallbackActivity activity -->
<activity
android:name="com.linusu.flutter_web_auth_2.CallbackActivity"
android:exported="true">
<intent-filter android:label="flutter_web_auth_2">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="YOUR_CALLBACK_URL_SCHEME_HERE" />
</intent-filter>
</activity>
</application>
</manifest> -
If you are targeting S+ (SDK version 31 and above) you need to provide an explicit value for
android:exported
. If you followed earlier installation instructions, this was not included. Make sure that you addandroid:exported="true"
to thecom.linusu.flutter_web_auth.CallbackActivity
activity in yourAndroidManifest.xml
file. -
Browser not closed after successful sign-in:
In order to ensure the
flutter_web_auth_2
works correctly, you need to remove anyandroid:taskAffinity
entries from yourAndroidManifest.xml
file. Setandroid:launchMode="singleTop"
to the main activity in yourAndroidManifest.xml
file.android/app/src/main/AndroidManifest.xml<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="@style/LaunchTheme"
// ...
/>