Okta Authentication with Appwrite
Tags: appwrite, okta, tutorial, authentication
Published: 2022-05-26 15:19:50

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 **[Okta](https://www.okta.com/)**. Let’s go ahead now to learn how we can set up Okta 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 Okta OAuth provider.

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


## 🔐 Configure Okta OAuth

Once our Appwrite project is up and running, we must create an Application Integration in the Okta Dashboard. Once you’re on the **Applications** page (under the Applications dropdown in the menu), just click on the **Create App Integration** button and create an app integration with the **Sign-in method** as **OIDC - OpenID Connect** and the **Application type** as **Web Application**.

![Okta New App](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eh3ycoavl45q3slud1f0.png)

Click on the **Next** button, fill in a suitable name for the app integration and copy the redirect URL from Appwrite’s Okta OAuth Setting dialog (by navigating to the OAuth Providers list in Users →Settings on the Appwrite Dashboard) to add to the **Allowed sign-in redirect URIs** field. Make sure to set the **Controlled access** field as per your application requirements.

![Okta App Name and Details](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9w8m3oazkva6nsy3j51v.png)

You will be redirected to your new Application Integration page, where you can find the Client ID,  Client Secret, and Okta Domain on the **General** tab. 

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

## 🤝 Enable Okta in Appwrite

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

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

>*Additionally, you can also [create a Custom Authorization Server](https://developer.okta.com/docs/guides/customize-authz-server/main/) and add the custom Authorization Server ID in Appwrite’s Okta OAuth setting dialog instead of leaving it empty for the `default` Authorization Server ID.*

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

Once you have set up Okta OAuth credentials in the Appwrite console, you are ready to implement Okta 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 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(
        "okta",
        "[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: "okta"
        );
    } 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 = "okta"
            )

        }
    }
}
```

### 🍎 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: "okta"
){ 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 Okta 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)