Auth0 Authentication with Appwrite
Tags: appwrite, auth0, tutorial, authentication
Published: 2022-05-26 14:32:25

For the longest time, Appwrite has supported an extensive list of external authentication providers to enable our developers to reduce friction for their users and give them the freedom to work with platforms they like. With the recent release of Appwrite 0.14, we added 3 new authentication providers, one of which was [**Auth0**](https://auth0.com/). Let’s go ahead now to learn how we can set up Auth0 authentication in our applications using Appwrite. 

>### New to Appwrite? 🤔

>[Appwrite](http://appwrite.io/) is an open-source back-end-as-a-service that abstracts all the complexity of building a modern application by providing a set of REST and Realtime APIs for your core back-end needs. Appwrite takes the heavy lifting for developers and handles user authentication and authorization, databases, file storage, cloud functions, webhooks, and much more!


## 📃 Prerequisites

To follow along with this tutorial, you’ll need access to an Appwrite project or permissions to create one. If you don’t already have an Appwrite server running, follow the official [installation tutorial](https://appwrite.io/docs/installation) to set one up. Once you create a project on the Appwrite console, you can head over to **Users →Settings** to find the list of the supported OAuth2 providers. This is where we will set up the Auth0 OAuth provider.

You will also need an Auth0 account, and if you don’t have one, you can easily create one for free by visiting [auth0.com](https://auth0.com).


## 🔐 Configure Auth0 OAuth

Once our Appwrite project is up and running, we must [create an Application](https://auth0.com/docs/get-started/auth0-overview/create-applications) in the Auth0 Dashboard. Once you’re on the Applications page, just click on the **Create** button and create an App with a suitable name with the **Regular Web Applications** type.

![Auth0 Create App](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m2vy1gu9m0knfuuwl4zz.png)

You will be redirected to your new App’s page, where you can find the Auth0 Domain, Client ID and Client Secret on the **Settings** tab. 

![Auth0 App Settings](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wuclghiww13ldlgz93k9.png)

## 🤝 Enable Auth0 in Appwrite

Visit **Users →Settings** on the Appwrite Dashboard and enable the Auth0 OAuth provider. You’ll be asked to enter the **Client ID**, **Client Secret** and **Auth0 Domain** from the previous step. Copy those from your Auth0 App’s Page and paste them into Appwrite’s OAuth setting dialog.

![Auth0 Appwrite Fields](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qnpno3p2ylodh9qjkw2l.png)

Copy the redirect URL from Appwrite’s Auth0 OAuth Setting dialog and paste it in the **Allowed Callback URLs** on the Settings tab on your Auth0 App’s page.

![Auth0 Allowed Callback URLs](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9trgst94irw19p9bohhn.png)

## 👨‍💻 Implement Sign In with Auth0 in Your Project

Once you have set up Auth0 OAuth credentials in the Appwrite console, you are ready to implement Auth0 Sign In in your project. Let's see how we can do it on various platforms.

You can use our client SDKs for various platforms to authenticate your users with OAuth2 providers. Before you can authenticate, you need to add our SDK as a dependency and configure it with an endpoint and project ID. To learn to configure our SDKs you can follow the getting started guide for each platform. The appropriate links are provided in each section below. Once you have the SDK configured, you can instantiate and call the account service to create a session from the OAuth2 provider. Below are the examples for different platforms to initialize clients and perform OAuth2 login.


### 🌐 Web

First you need to add a web platform in your project from the Appwrite console. Adding a web platform allows Appwrite to validate the request it receives and also prevents cross-origin errors in web. In the project settings page, click on **Add Platform** button and select **New Web App**. In the dialog box that appears, give a recognizable name to your platform and add the host name of your application.

![Add Web App](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lutvzqutge67j6nhmige.png)

Follow the [Getting Started for Web](https://appwrite.io/docs/getting-started-for-web) guide for detailed instruction on how to use Appwrite with your web application.

```js
const appwrite = new Appwrite();

appwrite
  .setEndpoint('[YOUR_END_POINT]')
  .setProject('[YOUR_PROJECT_ID]');

try {
    await appwrite.account.createOAuth2Session(
        "auth0",
        "[YOUR_END_POINT]/auth/oauth2/success",
        "[YOUR_END_POINT]/auth/oauth2/failure",
    );
} catch (error) {
    throw error;
}
```

### 📱 Flutter

For Flutter, in Android, to properly handle redirecting your users back to your mobile application after completion of OAuth flow, you need to set the following in your `AndroidManifest.xml` file.

```xml
<manifest ...>
  ...
  <application ...>
    ...
    <!-- Add this inside the `<application>` tag, alongside 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-[YOUR_PROJECT_ID]" />
      </intent-filter>
    </activity>
  </application>
</manifest>
```

You also need to add the Flutter platform in your project from the Appwrite console. Adding Flutter platforms allows Appwrite to validate the request it receives and also prevents requests from unknown applications. In the project settings page, click on **Add Platform** button and select **New Flutter App**. In the dialog box that appears, select the appropriate Flutter platform, give a recognizable name to your platform and add the application ID or package name based on the platform. You need to follow this step for each Flutter platform you will build your application for.


![Add Flutter App](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9yzg1gba3gjj36hpa4ah.png)

For more detailed instructions on getting started with Appwrite for Flutter developers follow our official [Getting Started for Flutter](https://appwrite.io/docs/getting-started-for-flutter) guide. Finally, you can call `account.createOAuth2Session` from your application as shown below.

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

void main() async {
    final client = new Client();

    client
    .setEndpoint('[YOUR_END_POINT]')
    .setProject('[YOUR_PROJECT_ID]');

    final account = Account(client);

    try {
        await account.createOAuth2Session(
            provider: "auth0"
        );
    } catch (error) {
        throw error;
    }
}
```

### 🤖 Android

For Android, to properly handle redirecting your users back to your mobile application after completion of OAuth flow, you need to set the following in your `AndroidManifest.xml` file.

```xml
<manifest ...>
  ...
  <application ...>
    ...
    <!-- Add this inside the `<application>` tag, alongside the existing `<activity>` tags -->
    <activity android:name="io.appwrite.views.CallbackActivity" android:exported="true">
      <intent-filter android:label="android_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-[YOUR_PROJECT_ID]" />
      </intent-filter>
    </activity>
  </application>
</manifest>
```

You also need to add the Android platform in your project from the Appwrite console. Adding Android platforms allows Appwrite to validate the request it receives and also prevents requests from unknown applications. In the project settings page, click on **Add Platform** button and select **New Android App**. In the dialog box that appears give your platform a recognizable name and add the package name of your application.

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

For more detailed instructions on getting started with Appwrite for Android developers follow our official [Getting Started for Android](https://appwrite.io/docs/getting-started-for-android) guide. Finally, you can call `account.createOAuth2Session` from your application as shown below.

```kotlin
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import io.appwrite.Client
import io.appwrite.services.Account

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val client = Client(applicationContext)
            .setEndpoint("[YOUR_ENDPOINT]") // Your API Endpoint
            .setProject("[YOUR_PROJECT_ID") // Your project ID

        val account = Account(client)

        GlobalScope.launch {
            account.createOAuth2Session(
                activity = this@MainActivity,
                provider = "auth0"
            )

        }
    }
}
```

### 🍎 Apple

To capture the Appwrite OAuth callback URL, the following URL scheme needs to add to your `Info.plist`.

```xml
<key>CFBundleURLTypes</key>
<array>
<dict>
    <key>CFBundleTypeRole</key>
    <string>Editor</string>
    <key>CFBundleURLName</key>
    <string>io.appwrite</string>
    <key>CFBundleURLSchemes</key>
    <array>
        <string>appwrite-callback-[YOUR_PROJECT_ID]</string>
    </array>
</dict>
</array>
```

You also need to add the Apple platform in your project from the Appwrite console. Adding Apple platforms allows Appwrite to validate the request it receives and also prevents requests from unknown applications. In the project settings page, click on **Add Platform** button and select **New Apple App**. In the dialog box that appears, select the appropriate Apple platform tab and give your platform a recognizable name and add the package name of your application. For each supported Apple platform you need to follow this process.


![Add Apple App](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qzyyoiy4h8qoq1n0tp8d.png)

For more detailed instructions on getting started with Appwrite for iOS developers follow our official [Getting Started for Apple](https://appwrite.io/docs/getting-started-for-apple) guide. Finally, you can call `account.createOAuth2Session` from your application as shown below.

```swift
import Appwrite

let client = Client()
    .setEndpoint("[YOUR_ENDPOINT]")
    .setProject("[YOUR_PROJECT_ID]")

let account = Account(client)

account.createOAuth2Session(
    provider: "auth0"
){ result in
    switch result {
    case .failure(let err):
        print(err.message)
    case .success:
        print("logged in")
    }
}
```

## 🏁 Conclusion

And that’s all it takes to implement Auth0 OAuth-based authentication with Appwrite. You can view the following resources as well if you want to explore Appwrite further:

* [Appwrite Docs](https://appwrite.io/docs)
* [Appwrite Discord](https://appwrite.io/discord)
* [Appwrite GitHub](https://github.com/appwrite/appwrite)