Skip to main content

Social / SSO login

There are different flows that the third party login provider may support:

  • Flow 1) Via authorisation code (one time use code) - for web and mobile apps.
    • a) If you have configred the client secret on the backend:
      • The frontend sends the auth code to the backend, the backend exchanges that with the provided client secret to get the access token. The access token is then used to fetch user info and log them in.
    • b) If you have not provided the client secret on the backend:
      • The backend uses PKCE flow to exchange the auth code with the user's access token. The access token is then used to fetch user info and log them in.
  • Flow 2) Via OAuth / access tokens - for mobile apps.
    • The access token is available on the frontend and is sent to the backend. SuperTokens then fetches user info using the access token and logs them in.
note

The same flow applies during sign up and sign in. If the user is signing up, the createdNewUser boolean on the frontend and backend will be true (as the result of the sign in up API call).

Flow 1a (Sign in with Google example)#

Step 1) Redirecting to social / SSO provider#

The first step is to fetch the URL on which the user will be authenticated. This can be done by querying the backend API exposed by SuperTokens (as shown below). The backend SDK automatically appends the right query params to the URL (like scope, client ID etc).

After we get the URL, we simply redirect the user there. In the code below, we will take an example of login with Google:

import { getAuthorisationURLWithQueryParamsAndSetState } from "supertokens-web-js/recipe/thirdparty";

async function googleSignInClicked() {
try {
const authUrl = await getAuthorisationURLWithQueryParamsAndSetState({
providerId: "google",

// This is where Google should redirect the user back after login or error.
// This URL goes on the Google's dashboard as well.
authorisationURL: "http://localhost:3000/auth/callback/google",
});

/*
Example value of authUrl: https://accounts.google.com/o/oauth2/v2/auth/oauthchooseaccount?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&access_type=offline&include_granted_scopes=true&response_type=code&client_id=1060725074195-kmeum4crr01uirfl2op9kd5acmi9jutn.apps.googleusercontent.com&state=5a489996a28cafc83ddff&redirect_uri=https%3A%2F%2Fsupertokens.io%2Fdev%2Foauth%2Fredirect-to-app&flowName=GeneralOAuthFlow
*/

// we redirect the user to google for auth.
window.location.assign(authUrl);
} catch (err: any) {
if (err.isSuperTokensGeneralError === true) {
// this may be a custom error message sent from the API by you.
window.alert(err.message);
} else {
window.alert("Oops! Something went wrong.");
}
}
}

Step 2) Handling the auth callback on your frontend#

Once the third party provider redirects your user back to your app, you need to consume the information to sign in the user. This requires you to:

  • Setup a route in your app that will handle this callback. We recommend something like http://localhost:3000/auth/callback/google (for Google). Regardless of what you make this path, remember to use that same path when calling the getAuthorisationURLWithQueryParamsAndSetState function in the first step.

  • On that route, call the following function on page load

    import { signInAndUp } from "supertokens-web-js/recipe/thirdparty";

    async function handleGoogleCallback() {
    try {
    const response = await signInAndUp();

    if (response.status === "OK") {
    console.log(response.user)
    if (response.createdNewUser) {
    // sign up successful
    } else {
    // sign in successful
    }
    window.location.assign("/home");
    } else {
    // SuperTokens requires that the third party provider
    // gives an email for the user. If that's not the case, sign up / in
    // will fail.

    // As a hack to solve this, you can override the backend functions to create a fake email for the user.

    window.alert("No email provided by social login. Please use another form of login");
    window.location.assign("/auth"); // redirect back to login page
    }
    } catch (err: any) {
    if (err.isSuperTokensGeneralError === true) {
    // this may be a custom error message sent from the API by you.
    window.alert(err.message);
    } else {
    window.alert("Oops! Something went wrong.");
    }
    }
    }
note

On success, the backend will send back session tokens as part of the response headers which will be automatically handled by our frontend SDK for you.

Special case for login with Apple#

Unlike other providers, Apple will not redirect your user back to your frontend app. Instead, it will redirect the user to your backend with a FORM POST request.

Our backend SDK will capture this request and redirect the user to your frontend app on your website domain on the /auth/callback/apple route (where /auth is the value of websiteBasePath set on the backend).

important

This means, that the value provided to the authorisationURL param in step 1, will be ignored and that on the Apple developer dashboard, you should set the redirect_uri to your API domain on the /auth/callback/apple route (where /auth is the value of apiBasePath set on the backend).

Flow 1b#

caution

Not supported by SuperTokens yet.

Social / SSO login for both, web and mobile apps#

If you have social / SSO login for your web and mobile app, then you might need to setup different client ID / secret for the same provider on the backend. For example, in case of Apple login, Apple gives you different client IDs for iOS login vs web & Android login (same client ID for web and Android).

In order to get this to work, you would need to call Apple.init twice on the backend (in the providers array). This causes an issue where when querying the signinup API, the backend would not know which client ID to use for the provider.

In order to solve this, you can:

  • Provide the client ID to the API calls mentioned above; OR
  • Set the isDefault to true on the backend provider config (as shown below) which means that in case the frontend doesn't pass a client ID in the signinup API call, that provider config will be used:
import { Apple } from "supertokens-node/recipe/thirdparty";

let providers = [
// Used for web and android login. These credentials will be used
// since isDefault is true, if the frontend doesn't pass a clientID to the
// signinup API call, it will use this one.
Apple({
isDefault: true,
clientId: "...",
clientSecret: {
keyId: "...",
privateKey: "...",
teamId: "...",
},
}),

// Used by iOS login. Notice that isDefault is not set here
Apple({
clientId: "...",
clientSecret: {
keyId: "...",
privateKey: "...",
teamId: "...",
},
}),
]

See also#