Skip to content

OAuth2 with todoist js

Marcos H edited this page May 6, 2017 · 2 revisions

This is a guide to implement OAuth authorization process with todoist-js. Before start, make sure you understand what we're talking about by reading a definition of OAuth.

Lets do it! preconditions: You should have implemented todoist-js as explained here and created an instance of the API client.

const todoist = new TodoistAPI();
  • Authorize

    • 1️⃣ Configure API client with your Todoist app credentials. Generate a random state string and keep it in browser session (localStorage maybe) to use it later.
    todoist.session.config({
      app_token: 'XXXXXXXXX', // your app token
      client_id: 'YYYYYYYYY', // your app id
      scope: 'data:read_write', // see docs for more scopes
      state: 'ZZZZZZZZZ', // some random string that you generated
    });
    • 2️⃣ Get the authorization url from todoist-js and redirect.
    const auth_url = todoist.session.requestAuthorizationUrl();
    window.location.href = auth_url;
    • 3️⃣ User will see login/authorization page and when confirm, user will return to your app (to the url you put in your Todoist app console field: OAuth Redirect URL
    • 4️⃣ Back in your code, check the presence of code and state in the Redirect URL. Something like https://my.todoistapp.com/?code=as7d68as8das76d87as6d87as6d&state=as98d9asd6978da6sf6a76
    • 5️⃣ If they're present, check that state parameter matches with your randomly generated string in step 1️⃣ (for security reasons), if so, you're ready to request an access token with given code parameter.
  • Exchange Access Token

    • 6️⃣ Using the code parameter received in authorization process, call a server script to exchange access token. This process requires a server side script due to Todoist API approach (see official response). Here is an example of a PHP script for exchange token. Taking that example of PHP for the url https://my.todoistapp.com/todoist-exchange.php you can call it like this:
    const exchangeToken = (auth_code) => {
      return fetch(`https://my.todoistapp.com/todoist-exchange.php?code=${auth_code}`, {
        method: 'GET',
        headers: {
          Accept: 'application/json, text/plain, */*',
          'Content-Type': 'application/json',
        },
        credentials: 'include',
      }).then(response => {
        return response.json();
      });
    }
    • 7️⃣ the response should include the access token, set it into todoist-js instance and you can start working with Todoist API v7 🙌
    // auth_code come from step 5
    exchangeToken(auth_code).then((response) => {
      todoist.session.accessToken = response.access_token;
    });

👉 Example codes are simplified for readability reasons 👈

Clone this wiki locally