Social Login (OAuth) with Mobile SDKs
Descope supports many social logins such as Google, Facebook, Microsoft, etc. You can find the currently supported list of social logins in the Descope console at Settings>Authentication Methods>Social Login (OAuth). The Descope console has the defaults set for all social logins. You can customize these by configuring the social logins with your company account.
Client SDK
Install SDK
// 1. Within XCode, go to File > Add Packages
// 2. Search for the URL of the git repo: https://github.com/descope/descope-swift
// 3. Configure your desired dependency rule
// 4. Click Add Package// 1. Within Android Studio, go to File > Project Structure > Dependencies > Add Dependency > 1 Library Dependency
// 2. Search for the dependency: "com.descope"
// 3. Configure your desired dependency rules
// 4. Click "Ok"// 1. From your Flutter project directory root, install the Descope SDK by running: flutter pub add descope
// 2. Or, add Descope to your pubspec.yml by including this line: descope: ^0.6.0
// View the package on pub.dev: https://pub.dev/packages/descope// 1. From your React Native project directory root, install the Descope SDK by running: npm i @descope/react-native-sdk
// View the package: https://github.com/descope/descope-react-nativeImport and initialize SDK
import DescopeKit
import AuthenticationServices
do {
Descope.setup(projectId: "__ProjectID__") { config in
// Optional: Only set baseURL if using a custom domain with Descope and managing token response with cookies
config.baseURL = "https://auth.app.example.com"
}
print("Successfully initialized Descope")
} catch {
print("Failed to initialize Descope")
print(error)
}import android.app.Application
import com.descope.Descope
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
try {
Descope.setup(this, projectId = "__ProjectID__") {
// Optional: Only set baseURL if using a custom domain with Descope and managing token response with cookies
baseUrl = "https://auth.app.example.com"
// Enable the logger
if (BuildConfig.DEBUG) {
logger = DescopeLogger()
}
}
} catch (e: Exception) {
Log.e("ERROR", e.stackTraceToString())
}
}
}import 'package:descope/descope.dart';
// Where your application state is being created
Descope.setup('<Your-Project-Id>', (config) {
// Optional: Only set baseURL if using a custom domain with Descope and managing token response with cookies
config.baseUrl = 'https://auth.app.example.com';
});
await Descope.sessionManager.loadSession();import { AuthProvider } from '@descope/react-native-sdk'
const AppRoot = () => {
return (
<AuthProvider
projectId="__ProjectID__"
// Optional: Only set baseURL if using a custom domain with Descope and managing token response with cookies
baseUrl = "https://auth.app.example.com"
>
<App />
</AuthProvider>
)
}Start OAuth
To initiate the OAuth process, call the OAuth initiation function after the user clicks the social login button. This function automatically opens the selected OAuth provider's login screen in a browser webview.
// Args:
// provider: social identity provider for authenticating the user. Supported values include OAuthProvider.facebook, OAuthProvider.github, OAuthProvider.google, OAuthProvider.microsoft, OAuthProvider.gitlab and OAuthProvider.apple. The current list can be found at https://github.com/descope/core-js-sdk/blob/main/src/sdk/oauth/types.ts in the OAuthProviders array.
let provider = OAuthProvider.facebook
// redirectURL: URL to return to after successful authentication with the social identity provider. You need to implement this page to access the token and finish oauth process (token exchange). The token arrives as a query parameter named 'code'.
let redirectURL = "exampleauthschema://auth.company.com/handle-oauth"
guard let session = Descope.sessionManager.session else { return }
var signInOptions: [SignInOptions] = [
.customClaims(["name": "{{user.name}}"]),
.mfa(refreshJwt: session.refreshJwt),
.stepup(refreshJwt: session.refreshJwt)
]
do {
let authURL = try await Descope.oauth.start(provider: provider, redirectURL: redirectURL, options: signInOptions)
guard let authURL = URL(string: authURL) else { return }
print("Successfully Initiated OAuth Authentication")
} catch {
print("Failed to Initiate OAuth Authentication")
print(error)
}// Args:
// provider: social identity provider for authenticating the user. Supported values include OAuthProvider.facebook, OAuthProvider.github, OAuthProvider.google, OAuthProvider.microsoft, OAuthProvider.gitlab and OAuthProvider.apple. The current list can be found at https://github.com/descope/core-js-sdk/blob/main/src/sdk/oauth/types.ts in the OAuthProviders array.
// redirectURL: URL to return to after successful authentication with the social identity provider. You need to implement this page to access the token and finish oauth process (token exchange). The token arrives as a query parameter named 'code'.
// options: optional options to get attributes like custom claims, stepup, mfa, and revoke sessions in response
try {
val provider = OAuthProvider.facebook
val redirectURL = "exampleauthschema://auth.company.com/handle-oauth"
// Use either the signUpOrIn, signUp, or signIn function
Descope.oauth.signUpOrIn(
provider,
redirectURL,
options = listOf(
SignInOptions.CustomClaims(mapOf("cc1" to "yes", "cc2" to true)),
SignInOptions.StepUp(session.refreshJwt),
SignInOptions.Mfa(session.refreshJwt),
SignInOptions.RevokeOtherSessions
)
)
} catch (e: Exception) {
Log.e("ERROR", e.stackTraceToString())
}/ Args:
// provider: social identity provider for authenticating the user. Supported values include OAuthProvider.facebook, OAuthProvider.github, OAuthProvider.google, OAuthProvider.microsoft, OAuthProvider.gitlab and OAuthProvider.apple. The current list can be found at https://github.com/descope/core-js-sdk/blob/main/src/sdk/oauth/types.ts in the OAuthProviders array.
const provider = OAuthProvider.facebook;
// redirectURL: URL to return to after successful authentication with the social identity provider. You need to implement this page to access the token and finish oauth process (token exchange). The token arrives as a query parameter named 'code'.
const redirectURL = 'exampleauthschema://my-app.com/handle-oauth';
// options: Optional options to get custom claims in response
const options = SignInOptions(customClaims: {'name': '{{user.name}}'});
// Choose an oauth provider out of the supported providers
// If configured globally, the redirect URL is optional. If provided however, it will be used
// instead of any global configuration.
final authUrl = await Descope.oauth.start(
provider: provider,
redirectUrl: redirectURL, options: options);// Args:
// provider: social identity provider for authenticating the user. Supported values include "facebook", "github", "google", "microsoft", "gitlab" and "apple". The current list can be found at https://github.com/descope/core-js-sdk/blob/main/src/sdk/oauth/types.ts in the OAuthProviders array.
const provider = "facebook"
// redirectURL: URL to return to after successful authentication with the social identity provider. You need to implement this page to access the token and finish oauth process (token exchange). The token arrives as a query parameter named 'code'.
const redirectURL = "exampleauthschema://auth.company.com/handle-oauth"
// loginOptions (LoginOptions): this allows you to configure behavior during the authentication process.
const loginOptions = {
"stepup": false,
"mfa": false,
"customClaims": {"claim": "Value1"},
"templateOptions": {"option": "Value1"}
}
// refreshToken (optional): the user's current refresh token in the event of stepup/mfa
const descopeSdk = useDescope();
const resp = await descopeSdk.oauth.start[provider](redirectURL, loginOptions);
if (!resp.ok) {
console.log("Failed to start oauth")
console.log("Status Code: " + resp.code)
console.log("Error Code: " + resp.error.errorCode)
console.log("Error Description: " + resp.error.errorDescription)
console.log("Error Message: " + resp.error.errorMessage)
}
else {
const provider_url = resp.data.url
console.log("Successfully started oauth. URL: " + provider_url)
}Finish OAuth
After successful authentication with your IdP the user is redirected to the redirect_url that you provide in the
oauth start function above. Your application should extract the code from the redirect_url and perform
token exchange as shown below.
// Args:
// authURL: the authURL generated from the Start OAuth
let authURL = "xxxxx"
do {
let session = ASWebAuthenticationSession(
url: authURL,
callbackURLScheme: "exampleauthschema") { callbackURL, error in
guard let url = callbackURL else {return}
let component = URLComponents(url: url, resolvingAgainstBaseURL: false)
guard let code = component?.queryItems?.first(where: {$0.name == "code"})?.value else { return }
// Exchange code for session
Task {
do {
let descopeSession = try await Descope.oauth.exchange(code: code)
print("Successfully completed OAuth Authentication")
print(descopeSession as Any)
} catch {
print("Failed to complete OAuth Authentication")
print(error)
}
}
}
session.presentationContextProvider = self
session.prefersEphemeralWebBrowserSession = true
session.start()
} catch {
print("Failed to complete OAuth Authentication")
print(error)
}// Args:
// authURL: the authURL generated from the Start OAuth
val code = "xxxxxx" // Code from authURL
try {
if (code != null) {
val descopeSession = Descope.oauth.exchange(code)
println("Successfully completed OAuth Authentication")
println(descopeSession)
}
} catch (exception: Exception) {
println("Failed to complete OAuth Authentication")
println(exception)
}// Args:
// authURL: the authURL generated from the Start OAuth
const authURL = "xxxxx"
// Redirect the user to the returned URL to start the OAuth redirect chain
final result = await FlutterWebAuth.authenticate(
url: authUrl, callbackUrlScheme: 'exampleauthschema');
// Extract the returned code
final code = Uri.parse(result).queryParameters['code'];
// Exchange code for an authentication response
final authResponse = await Descope.oauth.exchange(code: code!);// Args:
// code: code extracted from the url after user is redirected to redirectURL. The code is in the url as a query parameter "code" of the page.
const code = "xxxxx"
const descopeSdk = useDescope();
const response = await descopeSdk.oauth.exchange(code);
if (!resp.ok) {
console.log("Failed to finish oauth")
console.log("Status Code: " + resp.code)
console.log("Error Code: " + resp.error.errorCode)
console.log("Error Description: " + resp.error.errorDescription)
console.log("Error Message: " + resp.error.errorMessage)
}
else {
console.log("Successfully finished oauth.")
console.log(resp)
}Native OAuth
When running in iOS or Android, you can leverage the Sign in with Apple and Sign in with Google features to show a native authentication view that allows the user to login using the account they are already logged into on their device.
Before you can use these features, you will need to configure your application to support them. For iOS, you will need to complete the following Sign in with Apple configuration steps. For Android, you will need to complete the following configuration steps.
After configuration, you can use the following code to initiate the native authentication flow:
// Swift currently supports only iOS native authentication
do {
showLoading(true)
let authResponse = try await Descope.oauth.native(provider: .apple, options: [])
let session = DescopeSession(from: authResponse)
Descope.sessionManager.manageSession(session)
showHomeScreen()
} catch DescopeError.oauthNativeCancelled {
showLoading(false)
print("Authentication canceled")
} catch {
showError(error)
}try {
val context: Context = this@MyActivity
val provider = OAuthProvider.Google
val authRes = Descope.oauth.native(
context,
provider,
options = listOf(
SignInOptions.CustomClaims(mapOf("cc1" to "yes", "cc2" to true)),
SignInOptions.StepUp(session.refreshJwt),
SignInOptions.Mfa(session.refreshJwt),
SignInOptions.RevokeOtherSessions
)
)
println("Successfully completed OAuth Authentication")
println(authRes)
} catch (exception: Exception) {
println("Failed to complete OAuth Authentication")
println(exception)
}void loginWithOAuth() async {
AuthenticationResponse response;
if (!kIsWeb && Platform.isIOS) {
// created a custom Apple provider using the app bundle identifier as the Client ID
response = await Descope.oauth.native(provider: OAuthProvider.named("apple"));
} else if (!kIsWeb && Platform.isAndroid) {
// created a custom Google provider for implicit authentication
response = await Descope.oauth.native(provider: OAuthProvider.named("google"));
} else {
// regular web OAuth
}
final session = DescopeSession.fromAuthenticationResponse(response)
// ...
}Session Validation
The final step of completing the authentication with Descope is to validate the user session. Descope provides rich session management capabilities, including configurable session timeouts and logout functions. You can find the details and sample code for client session validation here.
Checkpoint
Your application is now integrated with Descope. Please test with sign-up or sign-in use case.