oauthtiktok

Example of Login with Tiktok (web) flow


I would like a user to login with tikok on the web and get his basic information like:

The Tiktok Login Kit for Web Documentation seems to be missing a full example on how to implement the full sequence of calls. Also some things are not explained at all (like the callback URL). Can someone share their full solution with code example on how to integrate tiktok login onto a webpage.


Solution

  • Heres a full example of the tiktok login for web implementation:

    1. setup a tiktok developer account https://developers.tiktok.com/

    2. create a new app, this will generate a CLIENT_KEY and CLIENT_SECRET.

    3. create 2 backend endpoints that you control, for example:

      • https://example.com/auth : builds a tiktok URL and redirects the user to that endpoint (where the user will be prompted to login).
      • https://example.com/authCallback : once the user has finished the login with tiktok flow, tiktok sends an authorizationResponse to this endpoint. The authorizationResponse contains info that you need to fetch the users data.
    4. in section "Platform Info": insert the callback URL and redirect domain. The callback URL being the second of the 2 server endpoints listed above. Tiktok will send the authorizationResponse to that URL once the user successfully loggs in and grants or declines the required permissions. In redirect domain simply add the domain without the exact path. Platform info

    5. fill out all info for your app and wait for approval, this can take up to 1-3 days.

    6. once approved, you are ready to implement the full flow, which consists of multiple steps/requests.

      (A) send the user from your frontend to your first backend endpoint https://example.com/auth. From there, the user will be redirected to the tiktok auth page.

      (B) once the user finished the authorization, tiktok sends a authorizationResponse to your callback URL (https://example.com/authCallback), which contains a variable code. With the code you can request the access_token and open_id of the user.

      (C) use the access_token and open_id to request basic user info.

    (A) Send User to Tiktok Authentication Page

    In your frontend, redirect the user to https://example.com/auth. Then run the following nodejs backend code on your /auth route. For this example we use an express app (req = request object, res = response object):

    // IMPORTANT, it is your responsibility to store a csrf token
    // in your database, to be able to prevent xss attacks, read more
    // here (section 2.1) =>  https://developers.tiktok.com/doc/login-kit-web
    const createCsrfState = () => Math.random().toString(36).substring(7);
    const csrfState = createCsrfState(); 
    res.cookie('csrfState', csrfState, { maxAge: 60000 });
    
    let url = 'https://open-api.tiktok.com/platform/oauth/connect/';
    
    url += `?client_key=${CLIENT_KEY}`;
    url += '&scope=user.info.basic';
    url += '&response_type=code';
    url += `&redirect_uri=${encodeURIComponent('https://example.com/authCallback')}`;
    url += '&state=' + csrfState;
    
    // redirect the user to the generated URL
    // user will be prompted to login with tiktok
    // and authorize needed permissions
    res.redirect(url);
    

    This code redirects the user to a tiktok url, where the user is prompted to sign in with tiktok and grant access. user is prompted to login

    (B) Handle authorizationResponse, use code to get access_token and open_id

    Once the user finished the login process, tiktok sends an authorizationResponse to your second backend server endpoint https://example.com/authCallback. In that callback you recieve variables state and code.

    // express example with
    // `req` = request object
    // `res` = response object
    
    // check if the csrf token is valid
    // its the developers responsibility
    // to setup a validation logic.
    if (!validateCsrfToken(req.query.state)) {
      throw new Error("invalid csrf token");
    }
    
    async function getAccessTokenAndOpenId(code, TIKTOK_CLIENT_KEY, TIKTOK_CLIENT_SECRET) {
      let urlAccessToken = 'https://open-api.tiktok.com/oauth/access_token/';
      urlAccessToken += '?client_key=' + TIKTOK_CLIENT_KEY;
      urlAccessToken += '&client_secret=' + TIKTOK_CLIENT_SECRET;
      urlAccessToken += '&code=' + code;
      urlAccessToken += '&grant_type=authorization_code';
      const resp = await axios.post(urlAccessToken);
      return {
        accessToken: resp.data.data.access_token,
        openId: resp.data.data.open_id,
      };
    }
    
    const code = req.query.code;
    const { openId, accessToken } = await getAccessTokenAndOpenId(code, TIKTOK_CLIENT_KEY, TIKTOK_CLIENT_SECRET);
    

    (C) Get basic user info

    async function getBasicInfo(accessToken, openId) {
      let urlBasicInfo = `https://open-api.tiktok.com/user/info/`;
      const data = {
        access_token: accessToken,
        open_id: openId,
        fields: [
          "open_id",
          "union_id",
          "avatar_url",
          "avatar_url_100",
          "avatar_url_200",
          "avatar_large_url",
          "display_name",
        ],
      };
      const resp = await axios.post(urlBasicInfo, data);
      return resp.data.data.user;
    }
    
    const userBasicInfo = await getBasicInfo(accessToken, openId);
    // 🥳 done!