Skip to content
This repository has been archived by the owner on Sep 29, 2023. It is now read-only.

Oauth provider guides #383

Draft
wants to merge 9 commits into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
348 changes: 348 additions & 0 deletions app/views/docs/oauth-providers/github.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,348 @@
# GitHub provider

Appwrite allows you to authenticate users using their GitHub account through the GitHub OAuth2 provider. OAuth authentication is a great way to reduce friction for your users and increase user conversion by simplifying the signup process. You can learn more about Appwrite's other OAuth2 providers [here](placeholder link).

## Enabling the GitHub provider
Before you can use GitHub to authenticate users, you need to enable the provider in your Appwrite console.
1. Navigate to your Appwrite project
2. Navigate to **Auth** > **Settings**
3. Find and open the OAuth provider
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
3. Find and open the OAuth provider
3. Find and open the OAuth2 provider

4. In the **Github OAuth2 Settings** modal, use the toggle to enable the provider
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
4. In the **Github OAuth2 Settings** modal, use the toggle to enable the provider
4. In the **GitHub OAuth2 Settings** modal, use the toggle to enable the provider

This is going to be fixed in 1.4.x:

image


Don't close this modal, we'll need to create a GitHub OAuth app to complete this form.

## Creating a GitHub OAuth app
To use GitHub OAuth with Appwrite, you need to create an OAuth app on your GitHub account or in your Github organization. You can do this by following the [Creating an OAuth App](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/creating-an-oauth-app) guide from GitHub. When prompted to provide a **Authorization callback URL**, provide the **URI** found in the **Github OAuth2 Settings** modal from your Appwrite console.
Copy link
Contributor

@stnguyen90 stnguyen90 Aug 2, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
To use GitHub OAuth with Appwrite, you need to create an OAuth app on your GitHub account or in your Github organization. You can do this by following the [Creating an OAuth App](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/creating-an-oauth-app) guide from GitHub. When prompted to provide a **Authorization callback URL**, provide the **URI** found in the **Github OAuth2 Settings** modal from your Appwrite console.
To use GitHub OAuth with Appwrite, you need to create an OAuth app on your GitHub account or in your GitHub organization. You can do this by following the [Creating an OAuth App](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/creating-an-oauth-app) guide from GitHub. When prompted to provide an **Authorization callback URL**, provide the **URI** found in the **Github OAuth2 Settings** modal from your Appwrite console.


After you've created your GitHub OAuth app, you can head back to your Appwrite console to complete the form in the **Github OAuth2 Settings** modal.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
After you've created your GitHub OAuth app, you can head back to your Appwrite console to complete the form in the **Github OAuth2 Settings** modal.
After you've created your GitHub OAuth app, you can head back to your Appwrite console to complete the form in the **GitHub OAuth2 Settings** modal.

- Find the **Client ID** in your GitHub OAuth app and provide this in the **App ID** field in the **Github OAuth2 Settings** modal from the Appwrite console.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
- Find the **Client ID** in your GitHub OAuth app and provide this in the **App ID** field in the **Github OAuth2 Settings** modal from the Appwrite console.
- Find the **Client ID** in your GitHub OAuth app and provide this in the **App ID** field in the **GitHub OAuth2 Settings** modal from the Appwrite console.

- Navigate to the **Client secrets** section in your Github OAuth app and click **Generate a new client secret**.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
- Navigate to the **Client secrets** section in your Github OAuth app and click **Generate a new client secret**.
- Navigate to the **Client secrets** section in your GitHub OAuth app and click **Generate a new client secret**.

- Copy your new client secret and provide this in the **App Secret** field in the **Github OAuth2 Settings** modal from the Appwrite console.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
- Copy your new client secret and provide this in the **App Secret** field in the **Github OAuth2 Settings** modal from the Appwrite console.
- Copy your new client secret and provide this in the **App Secret** field in the **GitHub OAuth2 Settings** modal from the Appwrite console.


## Authenticating
You can use any of the Appwrite Client SDKs to authenticate users with their GitHub account.

### Web
When a user calls the [Create OAuth2 Session](https://appwrite.io/docs/client/account#accountCreateOAuth2Session) endpoint in your web app, they will be taken to GitHub's OAuth page to complete their login.

After authenticating, they'll be redirected back to your app using either the `success` or `failure` URLs provided. To provide the best experience to your users, make sure to **implement and provide both routes** to prompt the user about successful and failed authentication attempts.

```js
import { Client, Account } from "appwrite";

const client = new Client();

const account = new Account(client);

client
.setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint
.setProject('[PROJECT_ID]') // Your project ID
;

// Go to OAuth provider login page
account.createOAuth2Session('github', '[LINK_ON_SUCCESS]', '[LINK_ON_FAILURE]');
```

### Flutter
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can use OAuth in your Flutter application, but some platforms like Android and Apple requires additional configuration to enable the OAuth callback, so the your users can be redirected back to your app..

#### Android OAuth callback

In order to capture the Appwrite OAuth callback url, the following activity needs to be added inside the `<application>` tag, along side the existing `<activity>` tags in your `AndroidManifest.xml`. Be sure to replace the `[PROJECT_ID]` string with your actual Appwrite project ID. You can find your Appwrite project ID in your project settings screen in your Appwrite console.

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

#### Apple
In order to capture the Appwrite OAuth callback url, the following URL scheme needs to added 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-[PROJECT_ID]</string>
</array>
</dict>
</array>
```

To authenticate a user in your Flutter application, use the [Create OAuth2 Session](https://appwrite.io/docs/client/account?sdk=flutter-default#accountCreateOAuth2Session) endpoint.

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

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

client
.setEndpoint('https://cloud.appwrite.io/v1') // YOUR API Endpoint
.setProject('[PROJECT_ID]') // YOUR PROJECT ID
;

// OAuth Login, for simplest implementation you can leave both success and
// failure link empty so that Appwrite handles everything.
await account.createOAuth2Session('github');

}
```

### Android (Kotlin)
Before you can add OAuth to your Android app, you need to setup a callback for your OAuth flow.

In order to capture the Appwrite OAuth callback url, the following activity needs to be added inside the `<application>` tag, along side the existing `<activity>` tags in your `AndroidManifest.xml`. Be sure to replace the `[PROJECT_ID]` string with your actual Appwrite project ID. You can find your Appwrite project ID in your project settings screen in your Appwrite console.

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

To authenticate a user in your Android application, use the [Create OAuth2 Session](https://appwrite.io/docs/client/account?sdk=android-kotlin#accountCreateOAuth2Session) endpoint.

```kotlin
import io.appwrite.Client
import io.appwrite.services.Account

val client = Client(context)
.setEndpoint("https://cloud.appwrite.io/v1") // Your API Endpoint
.setProject("[PROJECT_ID]") // Your project ID

val account = Account(client)

account.createOAuth2Session(
provider = "github",
)
```

### Android (Java)
Before you can add OAuth to your Android app, you need to setup a callback for your OAuth flow.

In order to capture the Appwrite OAuth callback url, the following activity needs to be added inside the `<application>` tag, along side the existing `<activity>` tags in your `AndroidManifest.xml`. Be sure to replace the `[PROJECT_ID]` string with your actual Appwrite project ID. You can find your Appwrite project ID in your project settings screen in your Appwrite console.

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

To authenticate a user in your Android application, use the [Create OAuth2 Session](https://appwrite.io/docs/client/account?sdk=android-java#accountCreateOAuth2Session) endpoint.

```java
import io.appwrite.Client;
import io.appwrite.coroutines.CoroutineCallback;
import io.appwrite.services.Account;

Client client = new Client(context)
.setEndpoint("https://cloud.appwrite.io/v1") // Your API Endpoint
.setProject("[PROJECT_ID]"); // Your project ID

Account account = new Account(client);

account.createOAuth2Session(
"github",
new CoroutineCallback<>((result, error) -> {
if (error != null) {
error.printStackTrace();
return;
}

Log.d("Appwrite", result.toString());
})
);
```

### iOS (Swift)

In order to capture the Appwrite OAuth callback url, the following URL scheme needs to added 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-[PROJECT_ID]</string>
</array>
</dict>
</array>
```

If you're using UIKit, you'll also need to add a hook to your `SceneDelegate.swift` file to ensure cookies work correctly.
```swift
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
guard let url = URLContexts.first?.url,
url.absoluteString.contains("appwrite-callback") else {
return
}
WebAuthComponent.handleIncomingCookie(from: url)
}
```

To authenticate a user in your Android application, use the [Create OAuth2 Session](https://appwrite.io/docs/client/account?sdk=apple-default#accountCreateOAuth2Session) endpoint.

```swift
import Appwrite

let client = Client()
.setEndpoint("https://cloud.appwrite.io/v1") // Your API Endpoint
.setProject("[PROJECT_ID]") // Your project ID

let account = Account(client)

let success = try await account.createOAuth2Session(
provider: "github"
)

```

## Refreshing the OAuth2 session
OAuth2 sessions expire to protect from security risks. This means, OAuth2 sessions should be refreshed to keep the user authenticated. You can do this by calling the [Update OAuth Session](https://appwrite.io/docs/client/account#accountUpdateSession) endpoint when ever your user visits your app.

### Web
```js
import { Client, Account } from "appwrite";

const client = new Client();

const account = new Account(client);

client
.setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint
.setProject('[PROJECT_ID]') // Your project ID
;

// Updates current session
const promise = account.updateSession('current');

promise.then(function (response) {
console.log(response); // Success
}, function (error) {
console.log(error); // Failure
});
```

### Flutter
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.


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

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

client
.setEndpoint('https://cloud.appwrite.io/v1') // YOUR API Endpoint
.setProject('[PROJECT_ID]'); // YOUR PROJECT ID

// Simplest implementation of updating an OAuth2 session
// prints Session Object value on success and error message on failure
try {
final future = await account.updateSession(sessionId: 'current');
print(future.toMap()); // Success
} on AppwriteException catch(e){
print(e.message); // Failure
}
}
```

### Android (Kotlin)
```kotlin
import io.appwrite.Client
import io.appwrite.services.Account

val client = Client(context)
.setEndpoint("https://cloud.appwrite.io/v1") // Your API Endpoint
.setProject("[PROJECT_ID]") // Your project ID

val account = Account(client)

val response = account.updateSession(
sessionId = "current"
)
```
### Android (Java)
```java
import io.appwrite.Client;
import io.appwrite.coroutines.CoroutineCallback;
import io.appwrite.services.Account;

Client client = new Client(context)
.setEndpoint("https://cloud.appwrite.io/v1") // Your API Endpoint
.setProject("[PROJECT_ID]"); // Your project ID

Account account = new Account(client);

account.updateSession(
"current"
new CoroutineCallback<>((result, error) -> {
if (error != null) {
error.printStackTrace();
return;
}

Log.d("Appwrite", result.toString());
})
);
```
### iOS (Swift)
``` swift
import Appwrite

let client = Client()
.setEndpoint("https://cloud.appwrite.io/v1") // Your API Endpoint
.setProject("[PROJECT_ID]") // Your project ID

let account = Account(client)

let session = try await account.updateSession(
sessionId: "current"
)
```