Generate Access Token

Learn to generate the access token required to call the YouTube Data API.

We'll cover the following

In this lesson, we'll utilize the OAuth credentials we created in the last lesson to produce the API access token.

Generate the access token

In the widget below, click the “Run” button to start the application. Then, click the URL under the widget below to open the application.

import React, { useEffect, useState } from "react";
import jwt_decode from "jwt-decode";
import youtubelogo from "../images/Youtubelogo.png";
import "bootstrap/dist/css/bootstrap.min.css";
const google = window.google;

const clientId = "{{CLIENT_ID}}";
function App() {
  const [profile, setProfileUser] = useState(null);
  const [tokenClient, settokenClient] = useState(null);
  const [accessToken, setaccessToken] = useState(null);

  function handleCallbackResponse(response) {
    const userObj = jwt_decode(response.credential);
    setProfileUser(userObj);
  }

  function getAccessToken() {
    tokenClient.requestAccessToken();
  }

  async function handleSignOut() {
    await google.accounts.id.disableAutoSelect();
    google.accounts.id.revoke(localStorage.getItem("gtoken"), () => {
      localStorage.removeItem("gtoken");
      setProfileUser(null);
    });
  }
  useEffect(() => {
    if(google) {
      google.accounts.id.initialize({
        client_id: clientId,
        callback: handleCallbackResponse,
      });
      google.accounts.id.renderButton(document.getElementById("sign-in-button"), {
        theme: "outline",
        size: "large",
      });

      settokenClient(google.accounts.oauth2.initTokenClient({
        client_id: clientId,
        scope:
        "https://www.googleapis.com/auth/youtube https://www.googleapis.com/auth/youtube.readonly https://www.googleapis.com/auth/youtube.force-ssl",
        callback: (tokenResponse) => {
        setaccessToken(tokenResponse.access_token);
        },
      }));
    }
  }, [accessToken, window.google, profile]);

  return (
    <div className="App">
        <div className="container d-flex justify-content-center" style={{paddingTop:"30px"}}>
          <img
            src={youtubelogo}
            alt="Youtube API"
            className="card-img-top mb-5"
            style={{maxWidth: "30vw",}}
          />
          <br />
        </div>
      <div id="main-body" className="container d-flex justify-content-center">
        {!profile && (
          <div id="sign-in-button" className="vstack d-flex justify-content-center align-items-center"></div>
        )}
        {profile && (
          <div className="row justify-content-center align-items-center">
            <div className="col-5 mt-4" style={{width: "40vw"}}>

              {accessToken && (
                <div className="input-group justify-content-center" style={{padding: '1rem'}}>
                  <span className="input-group-text"> Access Token</span>
                  <input
                    type="text"
                    className="form-control"
                    aria-label="Access Token"
                    id="accessToken"
                    aria-describedby="button-addon2"
                    readOnly
                    value={accessToken}
                  />
                  <button
                    className="btn btn-danger"
                    type="button"
                    id="button-addon2"
                    onClick={() => {
                    navigator.clipboard.writeText(
                      accessToken
                    );
                    }} >
                    Copy
                  </button>
                </div>
              )}
              {!accessToken && (
                <div className="input-group justify-content-center" style={{ padding: '1rem'}}>
                  <input
                  className="btn btn-danger"
                  type="submit"
                  onClick={getAccessToken}
                  value="Generate Access Token"
                  />
                </div>
              )}
              <div className="input-group justify-content-center" style={{paddingTop: "10px"}}>
                <button onClick={handleSignOut}className="btn btn-danger">Sign out</button>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

export default App;
Generating the access token

Note: The ACCESS_TOKEN will expire after 60 minutes. So, if the 401:Unauthorized error is encountered, feel free to come back to this lesson and create a new ACCESS TOKEN.

  1. Once we launch the application, a Google sign-in button will appear on the home page. Sign in with our Google account credentials by clicking the button.

  2. After we sign in to our Google account for the first time in the application, we must authorize the app by clicking the “Allow” button.

  3. Now, click the “Generate Access Token” button to open an authorization popup to continue to the GCP app. Choose an account to continue ahead and generate an access token.

  4. The access token is now visible on the screen. Copy the access token and paste it into the widget below. To save the token as an API key, enter it in the textbox and click the “Save” button.

  5. Now, verify the access token by clicking the “Run” button.

Press + to interact
verifyToken("{{ACCESS_TOKEN}}")

Now that we’ve created the API key, we’re ready to make our first call to the YouTube Data API!