DEV Community

Cover image for Okta Authentication with Appwrite
Aditya Oberai for Appwrite

Posted on

Okta Authentication with Appwrite

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. Let’s go ahead now to learn how we can set up Okta authentication in our applications using Appwrite.

New to Appwrite? 🤔

Appwrite 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 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.

🔐 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

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

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

🤝 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

Additionally, you can also create a Custom Authorization Server 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

Follow the Getting Started for Web guide for detailed instruction on how to use Appwrite with your web application.

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;
}
Enter fullscreen mode Exit fullscreen mode

📱 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.

<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>
Enter fullscreen mode Exit fullscreen mode

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

For more detailed instructions on getting started with Appwrite for Flutter developers follow our official Getting Started for Flutter guide. Finally, you can call account.createOAuth2Session from your application as shown below.

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;
    }
}
Enter fullscreen mode Exit fullscreen mode

🤖 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.

<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>
Enter fullscreen mode Exit fullscreen mode

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

For more detailed instructions on getting started with Appwrite for Android developers follow our official Getting Started for Android guide. Finally, you can call account.createOAuth2Session from your application as shown below.

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"
            )

        }
    }
}
Enter fullscreen mode Exit fullscreen mode

🍎 Apple

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

<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>
Enter fullscreen mode Exit fullscreen mode

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

For more detailed instructions on getting started with Appwrite for iOS developers follow our official Getting Started for Apple guide. Finally, you can call account.createOAuth2Session from your application as shown below.

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")
    }
}
Enter fullscreen mode Exit fullscreen mode

🏁 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:

Discussion (0)