Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

add Flutter authentication blog article

dshukertjra4e318e345bd
diff --git a/apps/www/_blog/2023-05-04-flutter-multi-factor-authentication.mdx b/apps/www/_blog/2023-05-04-flutter-multi-factor-authentication.mdx
index ad11ad53020..c160b6251d4 100644
--- a/apps/www/_blog/2023-05-04-flutter-multi-factor-authentication.mdx
+++ b/apps/www/_blog/2023-05-04-flutter-multi-factor-authentication.mdx
@@ -6,6 +6,7 @@ image: flutter-mfa/flutter-mfa-thumb-og.png
thumb: flutter-mfa/flutter-mfa-thumb.jpg
tags:
- flutter
+ - auth
date: '2023-05-04'
toc_depth: 2
---
diff --git a/apps/www/_blog/2023-07-18-flutter-authentication.mdx b/apps/www/_blog/2023-07-18-flutter-authentication.mdx
new file mode 100644
index 00000000000..550a9e1d7f8
--- /dev/null
+++ b/apps/www/_blog/2023-07-18-flutter-authentication.mdx
@@ -0,0 +1,426 @@
+---
+title: 'Getting started with Flutter authentication'
+description: Learn how authentication on Flutter works through Google sign in with Supabase auth.
+tags:
+ - flutter
+ - auth
+date: '2023-07-18'
+toc_depth: 2
+author: tyler_shukert
+image: flutter-authentication/flutter-authentication.png
+thumb: flutter-authentication/flutter-authentication.png
+---
+
+Flutter is Google’s open-source framework to develop cross-platform applications. In this article, we will take a look at how we can implement authentication using Google sign-in to secure our application using the [Supabase SDK for Flutter](https://supabase.com/docs/reference/dart/introduction).
+
+We will also dive into the deep ends of Open ID Connect sign-in to better understand how third-party sign-ins are being performed. You can check out the code of the sample in this article [here](https://github.com/supabase/supabase/tree/master/examples/auth/flutter-native-google-auth).
+
+## Prerequisites
+
+This article assumes you are comfortable with writing a basic application in Flutter. No knowledge of Supabase is required.
+
+We will use the following tools
+
+- [Flutter](https://docs.flutter.dev/get-started/install) - we used v3.10.5 for this article
+- Supabase - create your account [here](https://database.new/) if you do not have one
+- IDE of your choosing
+
+## What is Open ID Connect?
+
+We will implement third-party login with Google utilizing the Open ID Connect functionality of Supabase Auth. Open ID Connect, or OIDC is a protocol built on top of OAuth 2.0 that allows third-party applications to request the users to provide some personal information, such as name or profile image, in the form of an identity token along with an access token. This identity token can then be verified and decoded by the application to obtain that personal information.
+
+Supabase auth provides `signInWithIdToken` method where we can sign in a user using their ID token obtained from third-party auth providers such as Google. Upon signing a user with the `signInWithIdToken` method, Supabase automatically populates the content of the ID token in the Supabase user metadata for easy access to the information. We will be utilizing this feature in this example to display the user profile upon the user signing in.
+
+In today’s example, our app will make a request to Google, obtain the identity token, and we will use it to sign the user in as well as obtain basic user information.
+
+## What we will build
+
+We will build a simple app with a login screen and a home screen. The user is first presented with the login screen, and only after they sign in, can they proceed to the home screen. The login screen presents a login button that will kick off a third-party authentication flow to complete the sign-in. The profile screen displays user information such as the profile image or their full name.
+
+![Flutter Google sign in](/images/blog/flutter-authentication/flutter-google-sign-in.png)
+
+## Setup the Flutter project
+
+Let’s start by creating a fresh Flutter project.
+
+```bash
+flutter create myauthapp
+```
+
+then we can install the dependencies. Change the working directory to the newly created app directory and run the following command to install our dependencies.
+
+```dart
+flutter pub add supabase_flutter flutter_appauth crypto
+```
+
+We will use [supabase_flutter](https://pub.dev/packages/supabase_flutter) to interact with our Supabase instance. [flutter_appauth](https://pub.dev/packages/flutter_appauth) will be used to implement Google login, and [crypto](https://pub.dev/packages/crypto) is a library that has utility functions for encryption that we will use when performing OIDC logins.
+
+We are done installing our dependencies. Let’s set up [authentication](https://supabase.com/docs/guides/auth) now.
+
+## Configure Google sign-in on Supabase Auth
+
+We will obtain client IDs for iOS and Android from the Google Cloud console, and register them to our Supabase project.
+
+First, create your Google Cloud project [here](https://cloud.google.com/) if you do not have one yet. Within your Google Cloud project, follow the [Configure a Google API Console project for Android](https://developers.google.com/identity/sign-in/android/start-integrating#configure_a_project) guide and [Get an OAuth client ID for the iOS](https://developers.google.com/identity/sign-in/ios/start-integrating#get_an_oauth_client_id) guide to obtain client IDs for Android and iOS respectively.
+
+Once you have the client IDs, let’s add them to our Supabase dashboard. If you don’t have a Supabase project created yet, you can create one at [database.new](https://database.new) for free. The name is just an internal name, so we can call it “Auth” for now. Database Password will not be used in this example and can be reconfigured later, so press the `Generate a password` button and let Supabase generate a secure random password. No need to copy it anywhere. The region should be anywhere close to where you live, or where your users live in an actual production app.
+
+Lastly, for the pricing plan choose the free plan that allows you to connect with all major social OAuth providers and supports up to 50,000 monthly active users.
+
+![Supabase project creation](/images/blog/flutter-authentication/supabase-project-creation.png)
+
+Your project should be ready in a minute or two. Once your project is ready, you can open `authentication -> Providers -> Google` to set up Google auth. Toggle the `Enable Sign in with Google` switch first. Then add the two client IDs you obtained in your Google Cloud console to `Authorized Client IDs` field with a comma in between the two client IDs like this: `ANDROID_CLIENT_ID,IOS_CLIENT_ID`.
+
+![Supabase auth Google auth provider](/images/blog/flutter-authentication/supabase-google-provider.png)
+
+We also need some Android specific settings to make [flutter_appauth](https://pub.dev/packages/flutter_appauth#android-setup) work. Open `android/app/build.gradle` and find the `defaultConfig`. We need to set the reversed DNS form of the Android Client ID as the`appAuthRedirectScheme` manifest placeholder value.
+
+```groovy
+...
+android {
+ ...
+ defaultConfig {
+ ...
+ manifestPlaceholders += [
+ // *account_id* will be unique for every single app
+ 'appAuthRedirectScheme': 'com.googleusercontent.apps.*account_id*'
+ ]
+ }
+}
+```
+
+That is it for setting up our [Supabase auth to prepare for Google sign-in](https://supabase.com/docs/guides/auth/social-login/auth-google#using-native-sign-in).
+
+Finally, we can initialize Supabase in our Flutter application with the credentials of our Supabase instance. Update your `main.dart` file and add `Supabase.initialize()` in the `main` function like the following. Note that you will see some errors since the home screen is set to the `LoginScreen`, which we will create later.
+
+```dart
+import 'package:flutter/material.dart';
+import 'package:myauthapp/screens/login_screen.dart';
+import 'package:supabase_flutter/supabase_flutter.dart';
+
+void main() async {
+ /// TODO: update Supabase credentials with your own
+ await Supabase.initialize(
+ url: 'YOUR_SUPABASE_URL',
+ anonKey: 'YOUR_ANON_KEY',
+ );
+ runApp(const MyApp());
+}
+
+final supabase = Supabase.instance.client;
+
+class MyApp extends StatelessWidget {
+ const MyApp({super.key});
+
+ @override
+ Widget build(BuildContext context) {
+ return MaterialApp(
+ debugShowCheckedModeBanner: false,
+ title: 'Flutter Auth',
+ theme: ThemeData(
+ colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
+ useMaterial3: true,
+ ),
+ home: const LoginScreen(),
+ );
+ }
+}
+```
+
+You can find your Supabase URL and Anon key in `Settings -> API` from your [Supabase dashboard](https://supabase.com/dashboard/project/_/settings/api).
+
+![Supabase credentials](/images/blog/flutter-authentication/supabase-credentials.png)
+
+## Create the Login Screen
+
+We will have two screens for this app, `LoginScreen` and `ProfileScreen`. `LoginScreen` presents a single sign-in button for the user to perform Google sign-in. Create a `lib/screens/login_screen.dart` file add add the following.
+
+```dart
+import 'dart:convert';
+import 'dart:io';
+import 'dart:math';
+
+import 'package:crypto/crypto.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter_appauth/flutter_appauth.dart';
+import 'package:myauthapp/main.dart';
+import 'package:myauthapp/screens/profile_screen.dart';
+import 'package:supabase_flutter/supabase_flutter.dart';
+
+class LoginScreen extends StatefulWidget {
+ const LoginScreen({super.key});
+
+ @override
+ State<LoginScreen> createState() => _LoginScreenState();
+}
+
+class _LoginScreenState extends State<LoginScreen> {
+ @override
+ void initState() {
+ _setupAuthListener();
+ super.initState();
+ }
+
+ void _setupAuthListener() {
+ supabase.auth.onAuthStateChange.listen((data) {
+ final event = data.event;
+ if (event == AuthChangeEvent.signedIn) {
+ Navigator.of(context).pushReplacement(
+ MaterialPageRoute(
+ builder: (context) => const ProfileScreen(),
+ ),
+ );
+ }
+ });
+ }
+
+ /// Function to generate a random 16 character string.
+ String _generateRandomString() {
+ final random = Random.secure();
+ return base64Url.encode(List<int>.generate(16, (_) => random.nextInt(256)));
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return Scaffold(
+ appBar: AppBar(
+ title: const Text('Login'),
+ ),
+ body: Center(
+ child: ElevatedButton(
+ onPressed: () async {
+ const appAuth = FlutterAppAuth();
+
+ // Just a random string
+ final rawNonce = _generateRandomString();
+ final hashedNonce =
+ sha256.convert(utf8.encode(rawNonce)).toString();
+
+ /// TODO: update the iOS and Android client ID with your own.
+ ///
+ /// Client ID that you registered with Google Cloud.
+ /// You will have two different values for iOS and Android.
+ final clientId =
+ Platform.isIOS ? 'IOS_CLIENT_ID' : 'ANDROID_CLIENT_ID';
+
+ /// Set as reversed DNS form of Google Client ID + `:/` for Google login
+ final redirectUrl = '${clientId.split('.').reversed.join('.')}:/';
+
+ /// Fixed value for google login
+ const discoveryUrl =
+ 'https://accounts.google.com/.well-known/openid-configuration';
+
+ // authorize the user by opening the concent page
+ final result = await appAuth.authorize(
+ AuthorizationRequest(
+ clientId,
+ redirectUrl,
+ discoveryUrl: discoveryUrl,
+ nonce: hashedNonce,
+ scopes: [
+ 'openid',
+ 'email',
+ 'profile',
+ ],
+ ),
+ );
+
+ if (result == null) {
+ throw 'No result';
+ }
+
+ // Request the access and id token to google
+ final tokenResult = await appAuth.token(
+ TokenRequest(
+ clientId,
+ redirectUrl,
+ authorizationCode: result.authorizationCode,
+ discoveryUrl: discoveryUrl,
+ codeVerifier: result.codeVerifier,
+ nonce: result.nonce,
+ scopes: [
+ 'openid',
+ 'email',
+ ],
+ ),
+ );
+
+ final idToken = tokenResult?.idToken;
+
+ if (idToken == null) {
+ throw 'No idToken';
+ }
+
+ await supabase.auth.signInWithIdToken(
+ provider: Provider.google,
+ idToken: idToken,
+ nonce: rawNonce,
+ );
+ },
+ child: const Text('Google login'),
+ ),
+ ),
+ );
+ }
+}
+```
+
+In terms of UI, this page is very simple, it just has a basic `Scaffold` with an `AppBar`, and has a button right in the middle of the body. Upon pressing the button, Google sign in flow starts. The user is presented with a Google authentication screen where they will complete the consent to allow our application to sign the user in using a Google account, as well as allow us to view some personal information.
+
+![Google sign in](/images/blog/flutter-authentication/google-sign-in.png)
+
+Let’s break down what is going on within the `onPressed` callback of the sign in button.
+
+First, we are generating a [nonce](https://openid.net/specs/openid-connect-core-1_0.html#SelfIssuedDiscovery:~:text=auth_time%20response%20parameter.)-,nonce,-String%20value%20used), which is essentially just a random string. This string is later passed to Google after being hashed to verify that the ID token has not been tampered to prevent a man-in-the-middle attack.
+
+```dart
+// Random string to verify the integrity of the ID Token
+final rawNonce = _generateRandomString();
+final hashedNonce = sha256.convert(utf8.encode(rawNonce)).toString();
+```
+
+`clientId` and `applicationId` are the app-specific values. These will be used to the authentication request to Google later on.
+
+```dart
+ /// Client ID that you registered with Google Cloud.
+ /// You will have two different values for iOS and Android.
+ final clientId = Platform.isIOS ? 'IOS_CLIENT_ID' : 'ANDROID_CLIENT_ID';
+```
+
+`redirectUrl` is the URL at which the user will be redirected after a successful authentication request. For Google sign-in, we can set it to the reversed DNS form of the client ID followed by `:/`. `discoveryUrl` is a URL provided by Google that contains information about their Open ID configuration.
+
+```dart
+/// Set as reversed DNS form of Google Client ID + `:/` for Google login
+final redirectUrl = '${clientId.split('.').reversed.join('.')}:/';
+
+/// Fixed value for google login
+const discoveryUrl = 'https://accounts.google.com/.well-known/openid-configuration';
+```
+
+Then we are sending an authorization request to Google. This is where the user is taken to Google’s page to perform sign in and consent our app to obtain some personal information. Note that we are requesting three scopes here. `openid` and `email` are required by Supabase auth to complete the sign-in process. `profile` is not required by Supabase auth, but we are requesting it to display some profile information on the profile screen later on. We do not actually obtain the requested information in this step though. All we are doing is requesting an access token that has permission to obtain the personal information we have requested.
+
+```dart
+// Authorize the user by opening the concent page
+final result = await appAuth.authorize(
+ AuthorizationRequest(
+ clientId,
+ redirectUrl,
+ discoveryUrl: discoveryUrl,
+ nonce: hashedNonce,
+ scopes: [
+ 'openid',
+ 'email',
+ 'profile',
+ ],
+ ),
+);
+```
+
+Using the authorization token obtained in the previous step, we make the final request to Google’s auth server to obtain the personal information we asked for earlier. We get an ID token in return, which contains the personal information.
+
+```dart
+// Request the access and id token to google
+final tokenResult = await appAuth.token(
+ TokenRequest(
+ clientId,
+ redirectUrl,
+ authorizationCode: result.authorizationCode,
+ discoveryUrl: discoveryUrl,
+ codeVerifier: result.codeVerifier,
+ nonce: result.nonce,
+ scopes: [
+ 'openid',
+ 'email',
+ 'profile',
+ ],
+ ),
+);
+```
+
+And lastly, we pass the ID token we obtained from Google to Supabase to complete the sign-in on Supabase auth. Once the user is signed in, the auth state listener in the `initState` fires and takes the user to the `ProfileScreen`.
+
+```dart
+await supabase.auth.signInWithIdToken(
+ provider: Provider.google,
+ idToken: idToken,
+ nonce: rawNonce,
+);
+```
+
+## Create the Profile Screen
+
+The `ProfileScreen` will be just a simple UI presenting some of the information we obtained in the `LoginPage`. We can access the user data with `supabase.auth.currentUser`, where Supabase has saved the personal information in a property called `userMetadata`. In this example, we are displaying the `avatar_url` and `full_name` to display a basic profile page. Create a `lib/screens/profile_screen.dart` file and add the following.
+
+```dart
+import 'package:flutter/material.dart';
+import 'package:myauthapp/main.dart';
+import 'package:myauthapp/screens/login_screen.dart';
+
+class ProfileScreen extends StatelessWidget {
+ const ProfileScreen({super.key});
+
+ @override
+ Widget build(BuildContext context) {
+ final user = supabase.auth.currentUser;
+ final profileImageUrl = user?.userMetadata?['avatar_url'];
+ final fullName = user?.userMetadata?['full_name'];
+ return Scaffold(
+ appBar: AppBar(
+ title: const Text('Profile'),
+ actions: [
+ TextButton(
+ onPressed: () async {
+ await supabase.auth.signOut();
+ if (context.mounted) {
+ Navigator.of(context).pushReplacement(
+ MaterialPageRoute(builder: (context) => const LoginScreen()),
+ );
+ }
+ },
+ child: const Text('Sign out'),
+ )
+ ],
+ ),
+ body: Center(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ if (profileImageUrl != null)
+ ClipOval(
+ child: Image.network(
+ profileImageUrl,
+ width: 100,
+ height: 100,
+ fit: BoxFit.cover,
+ ),
+ ),
+ const SizedBox(height: 16),
+ Text(
+ fullName ?? '',
+ style: Theme.of(context).textTheme.headlineMedium,
+ ),
+ const SizedBox(height: 32),
+ ],
+ ),
+ ),
+ );
+ }
+}
+```
+
+And with that, we now have a basic working personalized application that utilizes Google sign-in.
+
+![Flutter Google sign in app](/images/blog/flutter-authentication/flutter-google-sign-in.png)
+
+## Conclusion
+
+In this post, we learned how to implement authentication in a Flutter application using Google sign-in and the Supabase SDK for Flutter. We also delved into the Open ID Connect functionality, which allows third-party sign-ins and the retrieval of personal information through identity tokens.
+
+You can also check out the [Flutter reference documents](https://supabase.com/docs/reference/dart/installing) to see how you can use `supabase-flutter` to implement a Postgres database, Storage, Realtime, and more.
+
+## More Flutter and Supabase resources
+
+- [supabase_flutter package](https://pub.dev/packages/supabase_flutter)
+- [Build a chat application using Flutter and Supabase](https://supabase.com/blog/flutter-tutorial-building-a-chat-app)
+- [Securing your Flutter apps with Multi-Factor Authentication](https://supabase.com/blog/flutter-multi-factor-authentication)
+- [How to build a real-time multiplayer game with Flutter Flame](https://supabase.com/blog/flutter-real-time-multiplayer-game)
diff --git a/apps/www/public/images/blog/flutter-authentication/flutter-authentication.png b/apps/www/public/images/blog/flutter-authentication/flutter-authentication.png
new file mode 100644
index 00000000000..bbc766e9edb
Binary files /dev/null and b/apps/www/public/images/blog/flutter-authentication/flutter-authentication.png differ
diff --git a/apps/www/public/images/blog/flutter-authentication/flutter-google-sign-in.png b/apps/www/public/images/blog/flutter-authentication/flutter-google-sign-in.png
new file mode 100644
index 00000000000..2a64b8ade38
Binary files /dev/null and b/apps/www/public/images/blog/flutter-authentication/flutter-google-sign-in.png differ
diff --git a/apps/www/public/images/blog/flutter-authentication/google-sign-in.png b/apps/www/public/images/blog/flutter-authentication/google-sign-in.png
new file mode 100644
index 00000000000..16ab7bb3e58
Binary files /dev/null and b/apps/www/public/images/blog/flutter-authentication/google-sign-in.png differ
diff --git a/apps/www/public/images/blog/flutter-authentication/supabase-credentials.png b/apps/www/public/images/blog/flutter-authentication/supabase-credentials.png
new file mode 100644
index 00000000000..2a99c5c37c4
Binary files /dev/null and b/apps/www/public/images/blog/flutter-authentication/supabase-credentials.png differ
diff --git a/apps/www/public/images/blog/flutter-authentication/supabase-google-provider.png b/apps/www/public/images/blog/flutter-authentication/supabase-google-provider.png
new file mode 100644
index 00000000000..c87dd8596be
Binary files /dev/null and b/apps/www/public/images/blog/flutter-authentication/supabase-google-provider.png differ
diff --git a/apps/www/public/images/blog/flutter-authentication/supabase-project-creation.png b/apps/www/public/images/blog/flutter-authentication/supabase-project-creation.png
new file mode 100644
index 00000000000..b9b39b2b784
Binary files /dev/null and b/apps/www/public/images/blog/flutter-authentication/supabase-project-creation.png differ