OAuth authentication allows users to log in using accounts from other popular services. This can be convenient for users because they can start using your app without creating a new account. It can also be more secure, because the user has one less password that could become vulnerable.
When using OAuth to authenticate, the authentication request is initiated from the client application. The user is then redirected to an OAuth 2 provider to complete the authentication step, and finally, the user is redirected back to the client application.
Configure OAuth 2 login
Before using OAuth 2 login, you need to enable and configure an OAuth 2 login provider.
Navigate to your Appwrite project.
Navigate to Auth > Settings.
Find and open the OAuth provider.
In the OAuth 2 settings modal, use the toggle to enable the provider.
Create and OAuth 2 app on the provider's developer platform.
Copy information from your OAuth2 provider's developer platform to fill the OAuth2 Settings modal in the Appwrite Console.
Configure redirect URL in your OAuth 2 provider's developer platform. Set it to URL provided to you by OAuth2 Settings modal in Appwrite Console.
Initialize OAuth 2 login
To initialize the OAuth 2 login process, use the Create OAuth 2 Session route.
OAuth2 sessions allow you to specify the scope of the access you want to request from the OAuth2 provider. The requested scopes describe which resources a session can access.
You can pass the scopes to request through the scopes parameter when creating a session. The scope is provider-specific and can be found in the provider's documentation.
import { Client, Account, OAuthProvider } from "appwrite";
const client = new Client()
.setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint
.setProject('<PROJECT_ID>'); // Your project ID
const account = new Account(client);
// Go to OAuth provider login page
account.createOAuth2Session(
OAuthProvider.Github, // provider
'https://example.com/success', // redirect here on success
'https://example.com/failed', // redirect here on failure
['repo', 'user'] // scopes (optional)
);
import 'package:appwrite/appwrite.dart';
import 'package:appwrite/enums.dart';
final client = Client()
.setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint
.setProject('<PROJECT_ID>'); // Your project ID
final account = Account(client);
// Go to OAuth provider login page
await account.createOAuth2Session(
provider: 'OAuthProvider.github',
scopes: ['repo', 'user']
);
For Apple, add the following URL scheme 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-<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.
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)
}
import Appwrite
import AppwriteEnums
let client = Client()
.setEndpoint("https://cloud.appwrite.io/v1") // Your API Endpoint
.setProject("<PROJECT_ID>") // Your project ID
let account = Account(client)
// Go to OAuth provider login page
try await account.createOAuth2Session(
provider: .github,
scopes: ['repo', 'user']
)
For Android, add the following activity inside the <application> tag in your AndroidManifest.xml. Replace <PROJECT_ID> with your actual Appwrite project ID.
<!-- 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>
import io.appwrite.Client
import io.appwrite.services.Account
import io.appwrite.enums.OAuthProvider
val client = Client()
.setEndpoint("https://cloud.appwrite.io/v1") // Your API Endpoint
.setProject("<PROJECT_ID>") // Your project ID
val account = Account(client)
// Go to OAuth provider login page
account.createOAuth2Session(
provider = OAuthProvider.GITHUB,
scopes = listOf('repo', 'user')
)
You'll be redirected to the OAuth 2 provider's login page to log in. Once complete, your user will be redirected back to your app.
You can optionally configure success or failure redirect links on web to handle success and failure scenarios.
OAuth 2 profile
After authenticating a user through their OAuth 2 provider, you can fetch their profile information such as their avatar image or name. To do this you can use the access token from the OAuth 2 provider and make API calls to the provider.
After creating an OAuth 2 session, you can fetch the session to get information about the provider.
import { Client, Account } from "appwrite";
const client = new Client();
const account = new Account(client);
const session = await account.getSession('current');
// Provider information
console.log(session.provider);
console.log(session.providerUid);
console.log(session.providerAccessToken);
An OAuth 2 session will have the following attributes.
Property | Description |
provider | The OAuth2 Provider. |
providerUid | User ID from the OAuth 2 Provider. |
providerAccessToken | Access token from the OAuth 2 provider. Use this to make requests to the OAuth 2 provider to fetch personal data. |
providerAccessTokenExpiry | Check this value to know if an access token is about to expire. |
You can use the providerAccessToken to make requests to your OAuth 2 provider. Refer to the docs for the OAuth 2 provider you're using to learn about making API calls with the access token.
Refresh tokens
OAuth 2 sessions expire to protect from security risks. This means the OAuth 2 session with a provider may expire, even when an Appwrite session remains active. OAuth 2 sessions should be refreshed periodically so access tokens don't expire.
Check the value of providerAccessTokenExpiry to know if the token is expired or is about to expire. You can refresh the provider session by calling the Update OAuth Session endpoint whenever your user visits your app. Avoid refreshing before every request, which might cause rate limit problems.
const promise = account.updateSession('[SESSION_ID]');
promise.then(function (response) {
console.log(response); // Success
}, function (error) {
console.log(error); // Failure
});
GraphQL
OAuth 2 is not available through the GraphQL API. You can use the REST API or any Client SDK instead.