Implementing OAuth on Flutter with Appwrite
Tags: appwrite, flutter, tutorial
Published: 2022-06-17 04:18:17



Today, we will learn to set up social authentication in our Flutter applications using Appwrite. By the end of this tutorial, you will know that setting up social authentication in the Flutter app using Appwrite is so easy that it can be done in a few minutes.

## Prerequisites

To take full advantage of this tutorial, you need the following:
- Access to the Appwrite project or permission to create one. If you don’t already have an Appwrite server running, follow the official installation tutorial to set up one.
- Flutter configured development machine.


## Source Code

To begin, clone the [repository](https://github.com/lohanidamodar/flappwrite_oauth) I’ve prepared for this tutorial where I have already set up a basic UI so that we can focus on implementing social login with Appwrite. We will start by adding and configuring the Appwrite SDK.


![Demo App](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/elic05pbvaqoah8lmh7u.png)
 

## Configure Appwrite’s SDK

First, open `pubspec.yaml` and add `appwrite: 4.0.2` as a dependency, and run `flutter pub get`.

```yaml
dependencies:
	appwrite: 4.0.2
```

Next open `main_screen.dart` and import the package.

```dart
import 'package:appwrite/appwrite.dart';
```

In the `_MainScreenState` , let’s configure the client.

First, create a client property.

```dart
class _MainScreenState extends State<MainScreen> {
	final Client client;
	...
}
```

Then in `initState` function, we configure the client.

```dart
client = Client();
client
	.setEndpoint('https://demo.appwrite.io/v1') // your endpoint
	.setProject('flappwrite_oauth'); // Yout project id
```

## Configure Discord OAuth

Either use an existing Appwrite project or create a new one. Go to **Users →Settings.** This is where we will set up the OAuth providers. Let’s first set up Discord. Click to turn on the Discord’s switch.

![Discord OAuth on Appwrite](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7oke8qgsp5t4lum06bj1.png)

We need to fill in the app ID and secret in the dialog that appears. We can get that from the Discord developer portal following the [official guide](https://discord.com/developers/docs/topics/oauth2). Copy the callback URL provided in the dialog and paste it into Discords setup for the redirect URL. Click Update once the app ID and secrets are filled.

![Discord OAuth Setup](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ik9hyasb2399q6d48n8w.png)
 
 
## Configure Google Sign In

In the Appwrite console, visit the Users→Settings page. There, find Google from the list and turn the switch on. To complete this, you will need an App ID and App Secret, which you can easily set up from Google API Console. Check out [their official documentation](https://support.google.com/googleapi/answer/6158849) for more details.

![Google OAuth on Appwrite](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cxf9hqsv3ac2de980rgo.png)
 
Once you get and fill in the Google **App ID** and the **App Secret**, you need to provide the callback URL shown in the dialog to the Google OAuth2's Authorized redirect URIs.

![Google OAuth Setup](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sz58qwt5vuzcnknx41ml.png)
 
Authorized JavaScript origins are required only for a web app. If you are also using Flutter web, you should add the URL as the Authorized JavaScript origins

Now that we have configured Google and Discord OAuth in the Appwrite console, we will implement this social auth in our Flutter application in the next section.

## Implement OAuth login on Appwrite

Before we can make any request to the Appwrite server from our applications, we need to add the platform we are building for [Appwrite.](http://Appwrite.In) On the project dashboard, click **Add Platform** → **New Flutter App**.

![Add Platform](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fwws3gwhznhdep8uz2s0.png)

In the dialog that appears, add the relevant platforms. I’ll be adding Android. If you want to add more than one platform, follow the same process for each platform.

![Add Flutter Android Platform](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lxb78p4w9nacfhynsmxd.png)

Next, in Android, to handle redirection successfully after the authentication is completed, we need to add the following to the `AndroidManifest.xml`.

```xml
<manifest ...>
  ...
  <application ...>
    ...
    <!-- Add this inside the `<application>` tag, along side the existing `<activity>` tags -->
    <activity android:name="com.linusu.flutter_web_auth.CallbackActivity" android:exported="true">
      <intent-filter android:label="flutter_web_auth">
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="appwrite-callback-[PROJECT_ID]" />
      </intent-filter>
    </activity>
  </application>
</manifest>
```

For iOS, version 12+ and macOS version 10.15+ are required for OAuth to work.

Finally, we can now log in with Google and Discord in our Application. It is straightforward. We instantiate `Account` with an instance of `Client` and call `createOAuth2Session`.

```dart
final account = Account(client);
account.createOAuth2Session(provider: 'google');
```

Open `main_screen.dart` find `_MainScreenState`, and there find the `handleLogin` function. This is called when we press Google login or Discord login buttons. We pass the respective provider, `google`, or `discord` as the param. Update the `handleLogin` function as the following.

```dart
handleLogin(String provider) async {
    await Account(client).createOAuth2Session(
      provider: provider,
    );
    checkedLoggedIn();
  }
```

The first thing to note, we only need to pass the provider and not the success and failure URL. Success and failure URLs are required only if we implement our own web application that handles completing the login process from the authorization code obtained from OAuth providers. However, this is handled by the Appwrite server internally, so we don’t need to provide the success and failure URLs.

Another thing to note, the log-in and sign-up process for OAuth-based authentication are the same, and the createOAuth2Session automatically creates a User if it doesn’t already exist in Appwrite. Also, if a user account already exists with the same email address, the OAuth session is linked to the same user account.

## Conclusion

Well, that’s all that is required to set up OAuth-based authentication with Appwrite. The final code can be found in the [final branch of the repository](https://github.com/lohanidamodar/flappwrite_oauth/tree/final). The challenging parts are setting up the specific provider and getting the client ID and secret from them. The rest is straightforward using Appwrite. Following resources can be handy if you want to explore Appwrite further.

- [Getting Started for Flutter](https://appwrite.io/docs/getting-started-for-flutter)
- [Appwrite Docs](https://appwrite.io/docs)
- [Appwrite Discord](https://appwrite.io/discord)
- [Appwrite Github](https://github.com/appwrite/appwrite)