WSO2 is now Choreo LabsLearn more

Trusted AI Governance
Build

Create agents and AI apps with the tools and languages your teams already use.

Connect

Link agents securely to your APIs, data, models and business systems.

Run

Deploy, observe and operate agents and AI apps reliably at any scale.

Govern

Control identity, access, cost and policy for every agent in production.

Agent Management

Developer Platform

  • API Management Cloud

    Design, secure and publish APIs with governance and analytics built in.

    Sign Up Now
  • Integration Cloud

    Connect apps, data and AI agents with low-code and pro-code integration.

    Sign Up Now
  • Identity & Access Management Cloud

    Secure sign-in and access for customers, partners, workforce and agents.

    Sign Up Now
  • Agent Management Cloud

    Build, run and govern AI agents with full visibility and control.

    Sign Up Now
  • Developer Platform Cloud

    Ship cloud-native apps faster on an internal developer platform.

    Sign Up Now

Self-Hosted

Full control over your stack. Deploy directly to your own servers, bare metal, cloud, or Kubernetes environment. Your data never leaves your perimeter.

Product Downloads
Choreo Labs
AI Governance
Platform
Solutions
Resources
Blog

Authenticate users into flutter applications using Asgardeo

Introduction

Flutter, introduced by Google, is an open-source software development kit (SDK) that enables developers to create high-quality and high-performance cross-platform applications for mobile, web, desktop, and embedded apps with a single codebase.

Asgardeo is a SaaS-based customer identity and access management (CIAM) solution that offers a wide range of identity and access management solutions for developers to embed in their applications, including user authentication, which can be integrated without requiring prior security expertise. 

For Flutter applications, Asgardeo serves as the CIAM provider, allowing application users to authenticate using their Asgardeo user account credentials.

In this tutorial, we will guide you through the process of integrating user authentication capability in a Flutter application using Asgardeo. As Flutter supports multiple platforms with a single codebase, we will focus on developing for the iOS platform. For detailed instructions on platform-specific development, please refer to Flutter's installation guide.

Authentication Flow

The following diagram illustrates the high-level authentication flow: 

  1. The application user starts the authentication process through the login option available in the Flutter application.
  2. The authentication request is sent to Asgardeo (the CIAM provider).
  3. The application user is prompted to the login page of Asgardeo.
  4. The application user enters their credentials.
  5. Asgardeo authenticates the application user and sends the authentication response to the Flutter application.
  6. The application user is authenticated to the Flutter application.

OIDC for Authentication

The Flutter application integrates with Asgardeo using the OIDC protocol, which is a standard way of supporting secure authentication, and identity and access management. OIDC supports several grant types, and here the Authorization Code flow is used. 

Prerequisites

  • Flutter SDK: Follow the Flutter Installation Guide to install the SDK, tools, and dependencies. 
  • Development environment: Set up any one of the following environments to edit and refactor your Flutter application code.
    • Android Studio
    • IntelliJ IDEA
    • Visual Studio Code
  • Sample application: Clone this repository to get the sample application. At this initial stage, the application contains sign in, view profile, and sign out options that let you navigate the pages. User authentication is not implemented yet. Furthermore, all profile information is hardcoded at the application level.

In this tutorial, we will walk you through the process of adding authentication capabilities to the application using Asgardeo as the CIAM provider. You will also learn how to retrieve and display the profile information of an authenticated user.

Step 1: install dependencies

Let’s start the integration by adding the required dependencies:

  • flutter_appauth : A wrapper package around AppAuth that provides functionalities for the authentication and authorization of users. This dependency will be used to communicate with Asgardeo to perform the user authentication. 
  • http: A composable, future-based library for making HTTP requests. This will be used to access Asgardeo server endpoints in the application flow.

To add these dependencies:

  • Update the `dependencies` section of the `pubspec.yaml` file located in the root directory of your project as follows:

  • dependencies: flutter: sdk: flutter http: ^0.12.1 flutter_appauth: ^4.2.1

  • Get them downloaded by running the ‘flutter pub get’ command in a terminal opened at the project root directory.

This tutorial uses Flutter version 3.3.10 and flutter_appauth version 4.2.1. Hence, the current implementation is only guaranteed to support those particular versions without any issues. You may find other available versions of flutter_appauth here. 

Step 2: configure the callback URL

The callback URL is the method by which Asgardeo communicates back with the application. Once the authentication process is complete, Asgardeo redirects users back to the location specified in the callback URL. 

iOS Setup

Update the <dict> element in the Runner/Info.plist file located in your iOS folder by adding the following entry:

 
<dict>
    ……
    ……
    <key>CFBundleURLTypes</key>
        <array>
            <dict>
                <key>CFBundleTypeRole</key>
                <string>Editor</string>
                <key>CFBundleURLSchemes</key>
                <array>
                    <string>wso2.asgardeo.sampleflutterapp</string>
                </array>
            </dict>
            </array>
 </dict>

Android/macOS Setup

Follow the Readme of the Flutter AppAuth plugin for the configurations required for macOS and Android. 

Step 3: register your application in Asgardeo

To integrate Asgardeo as your CIAM provider, you need to register your application as a Mobile Application in Asgardeo. Since you have chosen iOS as your development platform, you will register it as a mobile application. You can find instructions on how to register a mobile app in Asgardeo in this guide. 

Note: When registering the mobile application, make sure to add wso2.asgardeo.sampleflutterapp://login-callback as the authorized redirect URI. This is the same Callback URL added when configuring the Callback URL of the application.

Now the application can be integrated with any third-party OIDC mobile SDK to authenticate with Asgardeo. 

After registering your application with Asgardeo, you can enable user attributes for the application. These attributes correspond to the user's profile information that can be retrieved by the application with the user's consent.

Note: If you need additional attributes that are not listed in the user’s profile section by default, you can configure new attributes and retrieve them in the profile scope.

In this tutorial, you will retrieve the First Name, Last Name, Mobile, Country, Birth Date, and Photo URL as profile information.

Please note that only business users can log in to applications. Therefore, you need to create a new user to log in to this application.

Step 4: Integrate you application with Asgardeo

Follow the steps given below to integrate your application with Asgardeo:

  1. Add the following code snippet to the lib/main.dart file to import the required external packages:
            import 'dart:convert';
            import 'package:http/http.dart' as http;
            import 'package:flutter_appauth/flutter_appauth.dart';
            final FlutterAppAuth flutterAppAuth = FlutterAppAuth();
            

  2. Set the required variables by adding the following code snippet:

    const clientId = ‘<Client ID>’; const redirectUrl = '<Redirect URI>’; const discoveryUrl = '<Discovery>'; const userInfoEndpoint = '<UserInfo>';

Note: You can find the values of these parameters in the Quick Start and Info tabs of the registered application in Asgardeo.

clientId

This is the client ID of the application registered in Asgardeo.

Note: Client secrets are not issued for mobile apps since they are public clients. However, the PKCE (Proof Key for Code Exchange) extension is enabled by default as a security measure.

redirectUrl

(Required) This is the URI to which the authorization code is sent upon authentication and where the user is redirected upon logout.

Note: This is the URI given as the Authorized redirect URIs (eg: wso2.asgardeo.sampleflutterapp://login-callback) when the application in Asgardeo is created. This should be constructed by appending '://login-callback' to the callback URI we used in the Configuring theCallback URL for iOS section. (eg: wso2.asgardeo.sampleflutterapp).

discoveryUrl

This is the OpenID Connect Discovery endpoint in Asgardeo, which is used to discover Asgardeo’s metadata required to interact with it.

userInfoEndpoint

This is the endpoint in Asgardeo that is used to retrieve user profile information from Asgardeo.

Step 5: Implement the application logic

We need to modify the loginFunction(), retrieveUserDetails(), and logOutFunction() methods in the application. All these methods reside in the lib/main.dart file. 

LogIn Method

First, we need to initiate the two variables `_idToken` and ` _accessToken` in the ` _MyAppState` class and modify the `initState()` method to keep the received id token and access token in the login flow as below. 


class _MyAppState extends State<MyApp> { late int _pageIndex; late bool _isUserLoggedIn; late String? _idToken; late String? _accessToken; late String? _firstName; late String? _lastName; late String? _dateOfBirth; late String? _country; late String? _mobile; late String? _photo; @override void initState() { super.initState(); _pageIndex = 1; _isUserLoggedIn = false; _idToken = ''; _accessToken = ''; _firstName = ''; _lastName = ''; _dateOfBirth = ''; _country = ''; _mobile = ''; _photo = ''; } ………… ………… }

We can change the login method to authenticate application users to the system through Asgardeo. The authorizeAndExchangeCode() method in the flutter_appauth library handles the end-to-end authentication flow. 

We can replace the current implementation of the loginFunction() with the following code snippet:


Future<void> loginFunction() async { try { final AuthorizationTokenResponse? result = await flutterAppAuth.authorizeAndExchangeCode( AuthorizationTokenRequest( clientId, redirectUrl, discoveryUrl: discoveryUrl, promptValues: ['login'], scopes: ['openid', 'profile'], ), ); setState(() { _isUserLoggedIn = true; _idToken = result?.idToken; _accessToken = result?.accessToken; _pageIndex = 2; }); } catch (e, s) { print('Error while login to the system: $e - stack: $s'); setState(() { _isUserLoggedIn = false; }); } }

Here’s how the flow works in more detail:

  • The AuthorizationTokenRequest is created by passing the clientId, redirectUrl, discoveryUrl, and scopes. The scope parameter defines the actions that the Flutter application can perform on behalf of the user, and it will be used to retrieve the required user attributes by the application. The following are the scopes we defined in the request:
    1. `openid` - Performs the OIDC sign in
    2. `profile` - Retrieves the user's profile information
  • The AuthorizationTokenRequest object is then passed into appAuth.authorizeAndExchangeCode() to start the sign-in process. The user will be directed to Asgardeo’s sign-in page for authentication. As a result, AuthorizationTokenResponse is received. It contains two token types returned by Asgardeo.
    1. Access Token: A token represents access delegated to the client application by the user to access the user's protected resources. It has a specific scope and duration.
    2. ID Token: A security token represented as a JSON Web Token (JWT) that proves the user's successful authentication with Asgardeo. Furthermore, it contains other requested user profile information.

Retrieve User Information Method

Once the user has logged into the system, there is a section that shows the user's profile information. To obtain this information from Asgardeo, we will implement the retrieveUserDetails() method. This method uses the access token received in the login flow and includes it in the header section of the request as a bearer token to access the /userinfo endpoint. Then, the retrieved profile information response is parsed and set to the corresponding variables. 

You may notice that the ID token contains the same set of user information and wonder why we are using a different API call to fetch them separately. Calling the userinfo endpoint with the retrieved access token is an alternative way of retrieving the user’s profile information. Furthermore, this demonstrates how access tokens are used to access protected resources (such as the userinfo endpoint) on behalf of the user. 

You can use the following code snippet to replace the content of the retrieveUserDetails() method. 

  
Future<void> retrieveUserDetails() async {
    final userInfoResponse = await http.get(
      userInfoEndpoint,
      headers: {'Authorization': 'Bearer $_accessToken'},
    );

    if (userInfoResponse.statusCode == 200) {
      var profile = jsonDecode(userInfoResponse.body);
      setState(() {
        _firstName = profile['given_name'];
        _lastName = profile['family_name'];
        _dateOfBirth = profile['birthdate'];
        _country = profile['address']['country'];
        _mobile = profile['phone_number'];
        _photo = profile['picture'];
        _pageIndex = 3;
      });
    } else {
      throw Exception('Failed to get user profile information');
    }
  }

LogOut Method

Finally, change the logOutFunction() method, which performs the user logout. The following code snippet handles the user’s sign out functionality. 

 
void logOutFunction() async {
    try {
      final EndSessionResponse? result = await flutterAppAuth.endSession(
        EndSessionRequest(
          idTokenHint: _idToken,
          postLogoutRedirectUrl: redirectUrl,
          discoveryUrl: discoveryUrl,
        ),
      );

      setState(() {
        _isUserLoggedIn = false;
        _pageIndex = 1;
      });
    } catch (e, s) {
      print('Error while logout from the system: $e - stack: $s');
    }
  }

Try it out 

Let's walk through the end-to-end flow of the application we built in this tutorial.

  1. Run the Flutter application using the following command.
  2. flutter run

    After the application starts, you will see the login page with the Sign In option. 

  3. Click Sign In to start the authentication process.
  4. You will be redirected to Asgardeo's login page, where you enter valid user credentials. 

  5. Use the credentials of the user created in the Register the application in Asgardeo section.
  6. Upon the first login attempt, Asgardeo prompts for consent to share the configured attributes with the Flutter application. 

  7. Give your consent accordingly, allowing the application to access your profile information. 
  8. Once logged in, you will see a home page with the View profile and Sign out options. 
  9. Go to the Profile Information section by clicking View profile.

    You can now view the logged-in user's profile information. You can click Back to home to navigate back to the home page.

  10. Log out from the application by clicking Sign out.
  11. You get redirected back to the login page upon a successful logout.

Summary

In this tutorial, we demonstrated how to add authentication capability to a Flutter application using Asgardeo as the CIAM provider. The integration of authentication and authorization capabilities was made possible with the use of the Flutter AppAuth plugin.

We also provided a detailed guide on how to configure the application on Asgardeo. Starting with a sample Flutter application without user authentication implemented, we modified the sign-in, sign-out, and user info retrieval methods to successfully integrate authentication and profile info retrieval capabilities using Asgardeo.

The completed application's source code can be obtained here.
If you are interested in leveraging Asgardeo's CIAM features for your enterprise applications, please feel free to contact us for more information. Joining our growing community of developers is also highly encouraged!