# Login with TikTok

Streamline authentication in your app by enabling users to log in with their TikTok accounts.

Note
This implements a backend-to-backend integration for authentication. See [Backend Social Login APIs](/openapi/user/backend-social-login.openapi).

## How it works

In the backend-to-backend integration, Mosaic acts as a security layer safeguarding communication between your app and the social login provider, and enriching the user record with identity data from Mosaic.

When a user wants to log in to your app with their TikTok account, the client prompts the server side to initiate authentication with Mosaic ([Step 3](#step-3-start-tiktok-login)). Mosaic returns the TikTok authorization URL to redirect to in order to proceed with TikTok authentication. Once the user authenticates in TikTok, TikTok returns the authorization code to your server ([Step 4](#step-4-create-redirect-uri)), which then forwards it to Mosaic ([Step 5](#step-5-verify-tiktok-auth-code)). Mosaic exchanges this code for a TikTok token, and then returns transaction and user details to the server. The server has to ensure the user exists in Mosaic and create a new user if necessary ([Step 6](#step-6-retrieve-or-create-user-record)). Finally, the app server completes authentication by sending a request to Mosaic ([Step 7](#step-7-get-user-tokens)), which in turns provides user tokens. Upon token validation, the server signals the client side that the flow is complete and the user is logged in the app.

Mosaic APIs are shown in pink along with the relevant integration step, described below.


```mermaid
sequenceDiagram
participant U as User
participant C as Client
participant S as Backend
participant M as Mosaic
participant TikTok

U -->> C: Clicks "Log in with TikTok"
C -->> S: Log in with TikTok
note left of S: Step 3
S ->> M: POST /start with state
M ->> S: Authorization URL
S -->> TikTok: Authorization URL
note over U, TikTok: Auth with TikTok
note left of S: Step 4
TikTok -->> S: TikTok auth code & state
note left of S: Step 5
S ->> M: POST /verify (with TikTok code & state)
M -->> TikTok: Exchange code for token
TikTok -->> M: Token (social provider)
M ->> S: Return transaction_id, claims
note left of S: Step 6
S ->> M: User exists?
opt User exists in Mosaic
    M ->> S: Return user_id
end
opt User doesn't exist in Mosaic
    M ->> S: No user found
    S ->> M: Create new user
    M ->> S: Return user_id
end
note left of S: Step 7
S ->> M: POST /authenticate (transaction_id, user_id)
M ->> S: Tokens (Mosaic)
S -->> S: Validate tokens
S -->> C: Logged in
C -->> U: Done
```

## Before you start

Before you start your integration, you'll need a Mosaic application with an OIDC client. See [create an application](/guides/user/create_new_application).

Note
When creating a client, **Redirect URIs** is a required field. This flow doesn't use a Mosaic redirect URI so you can simply add your website URL (e.g., `https://your-domain.com`).

## Step 1: Register app in TikTok

Set up the TikTok developer account and register your app with TikTok, as described in [TikTok developer documentation](https://developers.tiktok.com/doc/getting-started-create-an-app). Upon the app registration, obtain the app's client ID and client secret, and submit the redirect URI to receive authorization codes from TikTok.

## Step 2: Configure TikTok auth method

In the Admin Portal, proceed to **B2C** or **B2B Identity** *based on your setup* > **Authentication methods** and select **TikTok**. Provide the following parameters obtained from Tiktok:

- **Client ID**: your app client ID as registered in TikTok
- **Client secret**: your app client secret as registered in TikTok
- **Redirect URI**: your app URL configured in TikTok to receive authorization codes


## Step 3: Start TikTok login

Implement sending a request like the one below to initiate an authentication flow using TikTok. The `redirect_uri` corresponds to the one added in [Step 2](#step-2-configure-tiktok-auth-method). To enhance protection against cross-site request forgery (CSRF) attacks, Mosaic recommends passing an optional parameter `state`—an opaque string generated by your backend.

This call returns the `authorization_url`—the TikTok's authorization URL. Your app should redirect the user to this endpoint in order to continue authenticating with TikTok.

Note
You'll need a valid client access token to authorize the request. See [Get client access tokens](/guides/user/retrieve_client_tokens).


```js
import fetch from 'node-fetch';

async function run() {
  const resp = await fetch(
    `https://api.transmitsecurity.io/cis/v1/auth/social/tiktok/start`,
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: 'Bearer <YOUR_TOKEN_HERE>'
      },
      body: JSON.stringify({
        redirect_uri: '<YOUR_APP_REDIRECT_URI>', // As configured in Admin Portal (Step 2)
        state: '<STATE>' // Opaque string, up to 50 characters
      })
    }
  );

  const data = await resp.json();
  console.log(data);
}

run();
```

## Step 4: Create redirect URI

Create a redirect URI —a backend GET endpoint that will receive the authorization `code` and `state` from TikTok as query parameters, for example `https://myapp.com/verify?code=123abc&state=abc123`. However, if an authentication error occurs during authentication with TikTok, the redirect URI will contain the error instead.

## Step 5: Verify TikTok auth code

Implement passing the auth `code` and `state` received to the redirect URI ([Step 4](#step-4-create-redirect-uri)) to Mosaic for verification using a call like the one below. If successful, a 200 response will be returned with `transaction_id` and `claims` object containing data extracted from the social provider (e.g., name, email, and unique identifiers from the social provider).

Protection agaist CSRF attacks
Mosaic will validate that the `state` parameter passed in this call matches the one initially submitted by your server in [Step 3](#step-3-start-tiktok-login).

Note
You'll need a valid client access token to authorize the request. See [Get client access tokens](/guides/user/retrieve_client_tokens).


```js
import fetch from 'node-fetch';

async function run() {
  const resp = await fetch(
    `https://api.transmitsecurity.io/cis/v1/auth/social/tiktok/verify`,
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: 'Bearer <YOUR_TOKEN_HERE>'
      },
      body: JSON.stringify({
        code: 'string', // Auth code returned by TikTok
        state: 'string' // State returned by TikTok
      })
    }
  );

  const data = await resp.json();
  console.log(data);
}

run();
```

## Step 6: Retrieve or create user record

Before trying to retrieve user tokens ([Step 7](#step-7-get-user-tokens)), your app has to ensure the user exists in Mosaic. If the user doesn't exist, the app has to create a new user in Mosaic before finalizing this authentication flow.

Important
This step is crucial as backend-to-backend integrations cannot provision new users just-in-time during authentication.

Locating a user entails mapping the TikTok user identifier returned in the `claims` object ([Step 5](#step-5-verify-tiktok-auth-code)) to the Mosaic's `user_id`. Depending on your implementation, this could be done differently. For example, if the app stores identifiers from social providers as `external_user_id`, this could mean sending a GET request to [Get user by external user ID](/openapi/user/user.openapi/other/getuserbyexternaluserid) endpoint with the TikTok identifier set as `external_user_id`. If the user exists, this call returns a user record with `user_id` needed for the [Step 7](#step-7-get-user-tokens). If the user doesn't exist, the "user not found" error is returned instead.

To create a new user in Mosaic, your app needs to send a POST request to the [Create user](/openapi/user/user.openapi/other/createuser) endpoint along with the TikTok identifier. Upon creating the user, Mosaic returns a user record with the `user_id` needed for the [Step 7](#step-7-get-user-tokens).

You might want to verify the user identity in a separate flow before proceeding with authentication.

## Step 7: Get user tokens

To complete authentication and retrieve the user access and ID tokens, your server should send a POST request like the one below with `transaction_id` ([Step 5](#step-5-verify-tiktok-auth-code)) and `user_id` ([Step 6](#step-6-retrieve-or-create-user-record)). If successful, a 200 response will be returned with the user tokens, which should be validated as described [here](/guides/user/validate_tokens). If the user doesn't exist, a "user not found" error will be returned.

Note
You'll need a valid client access token to authorize the request. See [Get client access tokens](/guides/user/retrieve_client_tokens).


```js
import fetch from 'node-fetch';

async function run() {
  const resp = await fetch(
    `https://api.transmitsecurity.io/cis/v1/auth/social/tiktok/authenticate`,
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: 'Bearer <YOUR_TOKEN_HERE>'
      },
      body: JSON.stringify({
        transaction_id: 'string', // Obtained in Step 5
        user_id: 'string' // Obtained in Step 5
      })
    }
  );

  const data = await resp.json();
  console.log(data);
}

run();
```