master 7c4872d343a6 cached
28 files
47.0 KB
11.8k tokens
22 symbols
1 requests
Download .txt
Repository: spotify/web-api-auth-examples
Branch: master
Commit: 7c4872d343a6
Files: 28
Total size: 47.0 KB

Directory structure:
gitextract_7i56fx55/

├── LICENSE
├── README.md
├── authorization/
│   ├── .gitignore
│   ├── authorization_code/
│   │   ├── README.md
│   │   ├── app.js
│   │   ├── package.json
│   │   └── public/
│   │       └── index.html
│   ├── authorization_code_pkce/
│   │   ├── README.md
│   │   ├── package.json
│   │   └── public/
│   │       ├── app.js
│   │       ├── index.html
│   │       └── style.css
│   ├── catalog-info.yaml
│   ├── client_credentials/
│   │   ├── README.md
│   │   └── app.js
│   └── implicit_grant/
│       ├── README.md
│       ├── app.js
│       ├── package.json
│       └── public/
│           └── index.html
├── catalog-info.yaml
└── get_user_profile/
    ├── .gitignore
    ├── README.md
    ├── index.html
    ├── package.json
    ├── src/
    │   ├── authCodeWithPkce.ts
    │   ├── script.ts
    │   └── types.d.ts
    └── tsconfig.json

================================================
FILE CONTENTS
================================================

================================================
FILE: LICENSE
================================================
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright 2012-2016 Spotify AB

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.


================================================
FILE: README.md
================================================
# Spotify Web API Examples

## Contents

- Authorization examples
    - [Authorization Code]( /authorization/authorization_code/)
    - [Authorization Code with PKCE extension]( /authorization/authorization_code_pkce/)
    - [Client Credentials](/authorization/client_credentials)
    - [Implicit Grant](/authorization/implicit_grant/)
- [Get User Profile example](/get_user_profile/)


================================================
FILE: authorization/.gitignore
================================================
node_modules/


================================================
FILE: authorization/authorization_code/README.md
================================================
# Spotify Authorization Code example

This app displays your Spotify profile information using [Authorization Code](https://developer.spotify.com/documentation/web-api/tutorials/code-flow)
to grant permissions to the app.

## Installation

This example runs on Node.js. On [its website](http://www.nodejs.org/download/) you can find instructions on how to install it.

Install the app dependencies running:

    $ npm install

## Using your own credentials

You will need to register your app and get your own credentials from the [Spotify for Developers Dashboard](https://developer.spotify.com/dashboard).

- Create a new app in the dashboard and add `http://localhost:8888/callback` to the app's redirect URL list.
- Once you have created your app, update the `client_id`, `redirect_uri`, and `client_secret` in the `app.js` file with the credentials obtained from the app settings in the dashboard.

## Running the example

From a console shell:

    $ npm start

Then, open `http://localhost:8888` in a browser.


================================================
FILE: authorization/authorization_code/app.js
================================================
/**
 * This is an example of a basic node.js script that performs
 * the Authorization Code oAuth2 flow to authenticate against
 * the Spotify Accounts.
 *
 * For more information, read
 * https://developer.spotify.com/documentation/web-api/tutorials/code-flow
 */

var express = require('express');
var request = require('request');
var crypto = require('crypto');
var cors = require('cors');
var querystring = require('querystring');
var cookieParser = require('cookie-parser');

var client_id = 'yourClientIDGoesHere'; // your clientId
var client_secret = 'YourSecretIDGoesHere'; // Your secret
var redirect_uri = 'http://localhost:8888/callback'; // Your redirect uri


const generateRandomString = (length) => {
  return crypto
  .randomBytes(60)
  .toString('hex')
  .slice(0, length);
}

var stateKey = 'spotify_auth_state';

var app = express();

app.use(express.static(__dirname + '/public'))
   .use(cors())
   .use(cookieParser());

app.get('/login', function(req, res) {

  var state = generateRandomString(16);
  res.cookie(stateKey, state);

  // your application requests authorization
  var scope = 'user-read-private user-read-email';
  res.redirect('https://accounts.spotify.com/authorize?' +
    querystring.stringify({
      response_type: 'code',
      client_id: client_id,
      scope: scope,
      redirect_uri: redirect_uri,
      state: state
    }));
});

app.get('/callback', function(req, res) {

  // your application requests refresh and access tokens
  // after checking the state parameter

  var code = req.query.code || null;
  var state = req.query.state || null;
  var storedState = req.cookies ? req.cookies[stateKey] : null;

  if (state === null || state !== storedState) {
    res.redirect('/#' +
      querystring.stringify({
        error: 'state_mismatch'
      }));
  } else {
    res.clearCookie(stateKey);
    var authOptions = {
      url: 'https://accounts.spotify.com/api/token',
      form: {
        code: code,
        redirect_uri: redirect_uri,
        grant_type: 'authorization_code'
      },
      headers: {
        'content-type': 'application/x-www-form-urlencoded',
        Authorization: 'Basic ' + (new Buffer.from(client_id + ':' + client_secret).toString('base64'))
      },
      json: true
    };

    request.post(authOptions, function(error, response, body) {
      if (!error && response.statusCode === 200) {

        var access_token = body.access_token,
            refresh_token = body.refresh_token;

        var options = {
          url: 'https://api.spotify.com/v1/me',
          headers: { 'Authorization': 'Bearer ' + access_token },
          json: true
        };

        // use the access token to access the Spotify Web API
        request.get(options, function(error, response, body) {
          console.log(body);
        });

        // we can also pass the token to the browser to make requests from there
        res.redirect('/#' +
          querystring.stringify({
            access_token: access_token,
            refresh_token: refresh_token
          }));
      } else {
        res.redirect('/#' +
          querystring.stringify({
            error: 'invalid_token'
          }));
      }
    });
  }
});

app.get('/refresh_token', function(req, res) {

  var refresh_token = req.query.refresh_token;
  var authOptions = {
    url: 'https://accounts.spotify.com/api/token',
    headers: { 
      'content-type': 'application/x-www-form-urlencoded',
      'Authorization': 'Basic ' + (new Buffer.from(client_id + ':' + client_secret).toString('base64')) 
    },
    form: {
      grant_type: 'refresh_token',
      refresh_token: refresh_token
    },
    json: true
  };

  request.post(authOptions, function(error, response, body) {
    if (!error && response.statusCode === 200) {
      var access_token = body.access_token,
          refresh_token = body.refresh_token;
      res.send({
        'access_token': access_token,
        'refresh_token': refresh_token
      });
    }
  });
});

console.log('Listening on 8888');
app.listen(8888);


================================================
FILE: authorization/authorization_code/package.json
================================================
{
  "name": "spotify-authorization-code-example",
  "version": "0.0.2",
  "description": "Spotify Authorization Code flow example",
  "author": "Spotify",
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "cookie-parser": "1.4.6",
    "cors": "2.8.5",
    "express": "4.18.2",
    "querystring": "~0.2.0",
    "request": "2.88.2"
  }
}


================================================
FILE: authorization/authorization_code/public/index.html
================================================
<!doctype html>
<html>
  <head>
    <title>Example of the Authorization Code flow with Spotify</title>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
    <style type="text/css">
      #login, #loggedin {
        display: none;
      }
      .text-overflow {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        width: 500px;
      }
    </style>
  </head>

  <body>
    <div class="container">
      <div id="login">
        <h1>This is an example of the Authorization Code flow</h1>
        <a href="/login" class="btn btn-primary">Log in with Spotify</a>
      </div>
      <div id="loggedin">
        <div id="user-profile">
        </div>
        <div id="oauth">
        </div>
        <button class="btn btn-default" id="obtain-new-token">Obtain new token using the refresh token</button>
      </div>
    </div>

    <script id="user-profile-template" type="text/x-handlebars-template">
      <h1>Logged in as {{display_name}}</h1>
      <div class="media">
        <div class="pull-left">
          <img class="media-object" width="150" src="{{images.0.url}}" />
        </div>
        <div class="media-body">
          <dl class="dl-horizontal">
            <dt>Display name</dt><dd class="clearfix">{{display_name}}</dd>
            <dt>Id</dt><dd>{{id}}</dd>
            <dt>Email</dt><dd>{{email}}</dd>
            <dt>Spotify URI</dt><dd><a href="{{external_urls.spotify}}">{{external_urls.spotify}}</a></dd>
            <dt>Link</dt><dd><a href="{{href}}">{{href}}</a></dd>
            <dt>Profile Image</dt><dd class="clearfix"><a href="{{images.0.url}}">{{images.0.url}}</a></dd>
            <dt>Country</dt><dd>{{country}}</dd>
          </dl>
        </div>
      </div>
    </script>

    <script id="oauth-template" type="text/x-handlebars-template">
      <h2>oAuth info</h2>
      <dl class="dl-horizontal">
        <dt>Access token</dt><dd class="text-overflow">{{access_token}}</dd>
        <dt>Refresh token</dt><dd class="text-overflow">{{refresh_token}}</dd>
      </dl>
    </script>

    <script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0-alpha.1/handlebars.min.js"></script>
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    <script>
      (function() {

        /**
         * Obtains parameters from the hash of the URL
         * @return Object
         */
        function getHashParams() {
          var hashParams = {};
          var e, r = /([^&;=]+)=?([^&;]*)/g,
              q = window.location.hash.substring(1);
          while ( e = r.exec(q)) {
             hashParams[e[1]] = decodeURIComponent(e[2]);
          }
          return hashParams;
        }

        var userProfileSource = document.getElementById('user-profile-template').innerHTML,
            userProfileTemplate = Handlebars.compile(userProfileSource),
            userProfilePlaceholder = document.getElementById('user-profile');

        var oauthSource = document.getElementById('oauth-template').innerHTML,
            oauthTemplate = Handlebars.compile(oauthSource),
            oauthPlaceholder = document.getElementById('oauth');

        var params = getHashParams();

        var access_token = params.access_token,
            refresh_token = params.refresh_token,
            error = params.error;

        if (error) {
          alert('There was an error during the authentication');
        } else {
          if (access_token) {
            // render oauth info
            oauthPlaceholder.innerHTML = oauthTemplate({
              access_token: access_token,
              refresh_token: refresh_token
            });

            $.ajax({
                url: 'https://api.spotify.com/v1/me',
                headers: {
                  'Authorization': 'Bearer ' + access_token
                },
                success: function(response) {
                  userProfilePlaceholder.innerHTML = userProfileTemplate(response);

                  $('#login').hide();
                  $('#loggedin').show();
                }
            });
          } else {
              // render initial screen
              $('#login').show();
              $('#loggedin').hide();
          }

          document.getElementById('obtain-new-token').addEventListener('click', function() {
            $.ajax({
              url: '/refresh_token',
              data: {
                'refresh_token': refresh_token
              }
            }).done(function(data) {
              access_token = data.access_token;
              oauthPlaceholder.innerHTML = oauthTemplate({
                access_token: access_token,
                refresh_token: refresh_token
              });
            });
          }, false);
        }
      })();
    </script>
  </body>
</html>



================================================
FILE: authorization/authorization_code_pkce/README.md
================================================
# Spotify Authorization Code with PKCE example

This app displays your Spotify profile information using [Authorization Code with PKCE](https://developer.spotify.com/documentation/web-api/tutorials/code-pkce-flow)
to grant permissions to the app.

## Using your own credentials

You will need to register your app and get your own credentials from the [Spotify for Developers Dashboard](https://developer.spotify.com/dashboard).

- Create a new app in the dashboard and add `http://localhost:8080` to the app's redirect URL list.
- Once you have created your app, update the `client_id` and `redirect_uri` in the `public/app.js` file with the values obtained from the app settings in the dashboard.

## Running the example

From a console shell:

    $ npm start

Then, open `http://localhost:8080` in a browser.


================================================
FILE: authorization/authorization_code_pkce/package.json
================================================
{
  "name": "spotify-authorization-code-pkce",
  "version": "1.0.0",
  "description": "Spotify Authorization Code with PKCE flow example",
  "scripts": {
    "start": "http-server --cors public"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "http-server": "^14.1.1"
  }
}


================================================
FILE: authorization/authorization_code_pkce/public/app.js
================================================
/**
 * This is an example of a basic node.js script that performs
 * the Authorization Code with PKCE oAuth2 flow to authenticate 
 * against the Spotify Accounts.
 *
 * For more information, read
 * https://developer.spotify.com/documentation/web-api/tutorials/code-pkce-flow
 */

const clientId = 'yourClientIDGoesHere'; // your clientId
const redirectUrl = 'eg:http://localhost:8080';        // your redirect URL - must be localhost URL and/or HTTPS

const authorizationEndpoint = "https://accounts.spotify.com/authorize";
const tokenEndpoint = "https://accounts.spotify.com/api/token";
const scope = 'user-read-private user-read-email';

// Data structure that manages the current active token, caching it in localStorage
const currentToken = {
  get access_token() { return localStorage.getItem('access_token') || null; },
  get refresh_token() { return localStorage.getItem('refresh_token') || null; },
  get expires_in() { return localStorage.getItem('refresh_in') || null },
  get expires() { return localStorage.getItem('expires') || null },

  save: function (response) {
    const { access_token, refresh_token, expires_in } = response;
    localStorage.setItem('access_token', access_token);
    localStorage.setItem('refresh_token', refresh_token);
    localStorage.setItem('expires_in', expires_in);

    const now = new Date();
    const expiry = new Date(now.getTime() + (expires_in * 1000));
    localStorage.setItem('expires', expiry);
  }
};

// On page load, try to fetch auth code from current browser search URL
const args = new URLSearchParams(window.location.search);
const code = args.get('code');

// If we find a code, we're in a callback, do a token exchange
if (code) {
  const token = await getToken(code);
  currentToken.save(token);

  // Remove code from URL so we can refresh correctly.
  const url = new URL(window.location.href);
  url.searchParams.delete("code");

  const updatedUrl = url.search ? url.href : url.href.replace('?', '');
  window.history.replaceState({}, document.title, updatedUrl);
}

// If we have a token, we're logged in, so fetch user data and render logged in template
if (currentToken.access_token) {
  const userData = await getUserData();
  renderTemplate("main", "logged-in-template", userData);
  renderTemplate("oauth", "oauth-template", currentToken);
}

// Otherwise we're not logged in, so render the login template
if (!currentToken.access_token) {
  renderTemplate("main", "login");
}

async function redirectToSpotifyAuthorize() {
  const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const randomValues = crypto.getRandomValues(new Uint8Array(64));
  const randomString = randomValues.reduce((acc, x) => acc + possible[x % possible.length], "");

  const code_verifier = randomString;
  const data = new TextEncoder().encode(code_verifier);
  const hashed = await crypto.subtle.digest('SHA-256', data);

  const code_challenge_base64 = btoa(String.fromCharCode(...new Uint8Array(hashed)))
    .replace(/=/g, '')
    .replace(/\+/g, '-')
    .replace(/\//g, '_');

  window.localStorage.setItem('code_verifier', code_verifier);

  const authUrl = new URL(authorizationEndpoint)
  const params = {
    response_type: 'code',
    client_id: clientId,
    scope: scope,
    code_challenge_method: 'S256',
    code_challenge: code_challenge_base64,
    redirect_uri: redirectUrl,
  };

  authUrl.search = new URLSearchParams(params).toString();
  window.location.href = authUrl.toString(); // Redirect the user to the authorization server for login
}

// Soptify API Calls
async function getToken(code) {
  const code_verifier = localStorage.getItem('code_verifier');

  const response = await fetch(tokenEndpoint, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: new URLSearchParams({
      client_id: clientId,
      grant_type: 'authorization_code',
      code: code,
      redirect_uri: redirectUrl,
      code_verifier: code_verifier,
    }),
  });

  return await response.json();
}

async function refreshToken() {
  const response = await fetch(tokenEndpoint, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: new URLSearchParams({
      client_id: clientId,
      grant_type: 'refresh_token',
      refresh_token: currentToken.refresh_token
    }),
  });

  return await response.json();
}

async function getUserData() {
  const response = await fetch("https://api.spotify.com/v1/me", {
    method: 'GET',
    headers: { 'Authorization': 'Bearer ' + currentToken.access_token },
  });

  return await response.json();
}

// Click handlers
async function loginWithSpotifyClick() {
  await redirectToSpotifyAuthorize();
}

async function logoutClick() {
  localStorage.clear();
  window.location.href = redirectUrl;
}

async function refreshTokenClick() {
  const token = await refreshToken();
  currentToken.save(token);
  renderTemplate("oauth", "oauth-template", currentToken);
}

// HTML Template Rendering with basic data binding - demoware only.
function renderTemplate(targetId, templateId, data = null) {
  const template = document.getElementById(templateId);
  const clone = template.content.cloneNode(true);

  const elements = clone.querySelectorAll("*");
  elements.forEach(ele => {
    const bindingAttrs = [...ele.attributes].filter(a => a.name.startsWith("data-bind"));

    bindingAttrs.forEach(attr => {
      const target = attr.name.replace(/data-bind-/, "").replace(/data-bind/, "");
      const targetType = target.startsWith("onclick") ? "HANDLER" : "PROPERTY";
      const targetProp = target === "" ? "innerHTML" : target;

      const prefix = targetType === "PROPERTY" ? "data." : "";
      const expression = prefix + attr.value.replace(/;\n\r\n/g, "");

      // Maybe use a framework with more validation here ;)
      try {
        ele[targetProp] = targetType === "PROPERTY" ? eval(expression) : () => { eval(expression) };
        ele.removeAttribute(attr.name);
      } catch (ex) {
        console.error(`Error binding ${expression} to ${targetProp}`, ex);
      }
    });
  });

  const target = document.getElementById(targetId);
  target.innerHTML = "";
  target.appendChild(clone);
}


================================================
FILE: authorization/authorization_code_pkce/public/index.html
================================================
<!DOCTYPE html>
<html>

<head>
  <title>Example of the Authorization Code with PKCE flow with Spotify</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>

  <div id="main"></div>
  <div id="oauth"></div>

  <template id="login">
    <h1>Welcome to the OAuth2 PKCE Example</h1>
    <button id="login-button" data-bind-onclick="loginWithSpotifyClick();"> Log in with Spotify </button>
  </template>

  <template id="logged-in-template">
    <h1>Logged in as <span data-bind="display_name"></span></h1>
    <img width="150" data-bind-src="images[0].url" data-bind-alt="display_name" />
    <table>
      <tr>
        <td>Display name</td>
        <td data-bind="display_name"></td>
      </tr>
      <tr>
        <td>Id</td>
        <td data-bind="id"></td>
      </tr>
      <tr>
        <td>Email</td>
        <td data-bind="email"></td>
      </tr>
      <tr>
        <td>Spotify URI</td>
        <td>
          <a data-bind="external_urls.spotify" data-bind-href="external_urls.spotify"></a>
        </td>
      </tr>
      <tr>
        <td>Link </dt>
        <td>
          <a data-bind="href" data-bind-href="href"></a>
        </td>
      </tr>
      <tr>
        <td>Profile Image</td>
        <td>
          <a data-bind-href="images[0].url" data-bind="images[0].url"></a>
        </td>
      </tr>
      <tr>
        <td>Country</td>
        <td data-bind="country"></td>
      </tr>
    </table>

    <button id="refresh-token-button" data-bind-onclick="refreshTokenClick();">Refresh Token</button>
    <button id="logout-button" data-bind-onclick="logoutClick();">Log out</button>
  </template>

  <template id="oauth-template">
    <h2>oAuth info</h2>
    <table>
      <tr>
        <td>Access token</td>
        <td data-bind="access_token"></td>
      </tr>
      <tr>
        <td>Refresh token</td>
        <td data-bind="refresh_token"></td>
      </tr>
      <tr>
        <td>Expiration at</td>
        <td data-bind="expires">${getExpirationDate(expires_in)}</td>
      </tr>
    </table>
  </template>

  <script src="app.js" type="module"></script>
</body>

</html>


================================================
FILE: authorization/authorization_code_pkce/public/style.css
================================================
body {
    margin: 1rem;
    font-family: Arial, Helvetica, sans-serif;
}

tr:nth-child(even) {
    background-color: #eee;
}

td:first-child {
    font-weight: bold;
}

td {
    white-space: nowrap;
    padding: 10px;
    margin-right: 1rem;
}

button {
    margin: 1rem 1rem 0 0;
    border: 0;
    border-radius: 20px;
    padding: 10px 3rem;
    font-size: 0.8rem;
    font-family: Arial, Helvetica, sans-serif;
    text-transform: uppercase;
    font-weight: bold;
    background-color:#1ed760;
    color: black;
}

button:hover {
    background-color: #1fdf64;
}

#logged-in {
    display: none;
}


================================================
FILE: authorization/catalog-info.yaml
================================================
apiVersion: backstage.io/v1alpha1
kind: Component
metadata:
  name: web-api-auth-examples
spec:
  type: library
  owner: opx-partner-activation


================================================
FILE: authorization/client_credentials/README.md
================================================
# Spotify Client Credentials example

This app retrieves information from an artist's track using [Client Credentials](https://developer.spotify.com/documentation/web-api/tutorials/code-flow)
to grant permissions to the app.

## Installation

This example runs on Node.js. On [its website](http://www.nodejs.org/download/) you can find instructions on how to install it.

### Using your own credentials

You will need to register your app and get your own credentials from the [Spotify for Developers Dashboard](https://developer.spotify.com/dashboard).

- Create a new app in the dashboard and add `http://localhost:8888/callback` to the app's redirect URL list.
- Once you have created your app, update the `client_id` and `client_secret` in the `app.js` file with the credentials obtained from the app settings in the dashboard.

## Running the example

From a console shell:

    $ node app.js


================================================
FILE: authorization/client_credentials/app.js
================================================
/**
 * This is an example of a basic node.js script that performs
 * the Client Credentials oAuth2 flow to authenticate against
 * the Spotify Accounts.
 *
 * For more information, read
 * https://developer.spotify.com/documentation/web-api/tutorials/client-credentials-flow
 */

const client_id = 'YourClientId'; 
const client_secret = 'YourClientSecret';

async function getToken() {
  const response = await fetch('https://accounts.spotify.com/api/token', {
    method: 'POST',
    body: new URLSearchParams({
      'grant_type': 'client_credentials',
    }),
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Authorization': 'Basic ' + (Buffer.from(client_id + ':' + client_secret).toString('base64')),
    },
  });

  return await response.json();
}

async function getTrackInfo(access_token) {
  const response = await fetch("https://api.spotify.com/v1/tracks/4cOdK2wGLETKBW3PvgPWqT", {
    method: 'GET',
    headers: { 'Authorization': 'Bearer ' + access_token },
  });

  return await response.json();
}

getToken().then(response => {
  getTrackInfo(response.access_token).then(profile => {
    console.log(profile)
  })
});


================================================
FILE: authorization/implicit_grant/README.md
================================================
# Spotify Implicit Grant example

This app displays your Spotify profile information using [Implicit Grant](https://developer.spotify.com/documentation/web-api/tutorials/implicit-flow)
to grant permissions to the app.

> The implicit grant flow has some significant security flaws, so we strongly advise against using this flow. If you need to implement authorization where storing your client secret is not possible, use Authorization code with PKCE instead.

## Installation

This example runs on Node.js. On [its website](http://www.nodejs.org/download/) you can find instructions on how to install it.

Install the app dependencies running:

    $ npm install

## Using your own credentials

You will need to register your app and get your own credentials from the [Spotify for Developers Dashboard](https://developer.spotify.com/dashboard).

- Create a new app in the dashboard and add `http://localhost:8080` to the app's redirect URL list.
- Once you have created your app, update the `client_id` and `redirect_uri` in the `public/index.html` file with the values obtained from the app settings in the dashboard.

## Running the example

From a console shell:

    $ npm start

Then, open `http://localhost:8080` in a browser.


================================================
FILE: authorization/implicit_grant/app.js
================================================
/**
 * This is an example of a basic node.js script that performs
 * the Implicit Grant oAuth2 flow to authenticate against
 * the Spotify Accounts.
 *
 * For more information, read
 * https://developer.spotify.com/documentation/web-api/tutorials/implicit-flow
 */

var express = require('express'); // Express web server framework
var app = express();
app.use(express.static(__dirname + '/public'));
console.log('Listening on 8888');
app.listen(8888);


================================================
FILE: authorization/implicit_grant/package.json
================================================
{
  "name": "spotify-implicit-grant-example",
  "version": "0.0.2",
  "description": "Spotify Implicit Grant example",
  "author": "Spotify",
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "express": "4.18.2"
  }
}


================================================
FILE: authorization/implicit_grant/public/index.html
================================================
<!doctype html>
<html>
  <head>
    <title>Example of the Implicit Grant flow with Spotify</title>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
    <style type="text/css">
      #login, #loggedin {
        display: none;
      }
      .text-overflow {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        width: 500px;
      }
    </style>
  </head>

  <body>
    <div class="container">
      <div id="login">
        <h1>This is an example of the Implicit Grant flow</h1>
        <button id="login-button" class="btn btn-primary">Log in with Spotify</button>
      </div>
      <div id="loggedin">
        <div id="user-profile">
        </div>
        <div id="oauth">
        </div>
      </div>
    </div>

    <script id="user-profile-template" type="text/x-handlebars-template">
      <h1>Logged in as {{display_name}}</h1>
      <div class="media">
        <div class="pull-left">
          <img class="media-object" width="150" src="{{images.0.url}}" />
        </div>
        <div class="media-body">
          <dl class="dl-horizontal">
            <dt>Display name</dt><dd class="clearfix">{{display_name}}</dd>
            <dt>Id</dt><dd>{{id}}</dd>
            <dt>Email</dt><dd>{{email}}</dd>
            <dt>Spotify URI</dt><dd><a href="{{external_urls.spotify}}">{{external_urls.spotify}}</a></dd>
            <dt>Link</dt><dd><a href="{{href}}">{{href}}</a></dd>
            <dt>Profile Image</dt><dd class="clearfix"><a href="{{images.0.url}}">{{images.0.url}}</a></dd>
            <dt>Country</dt><dd>{{country}}</dd>
          </dl>
        </div>
      </div>
    </script>

    <script id="oauth-template" type="text/x-handlebars-template">
      <h2>oAuth info</h2>
      <dl class="dl-horizontal">
        <dt>Access token</dt><dd class="text-overflow">{{access_token}}</dd>
      </dl>
    </script>

    <script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0-alpha.1/handlebars.min.js"></script>
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    <script>
      (function() {

        var stateKey = 'spotify_auth_state';

        /**
         * Obtains parameters from the hash of the URL
         * @return Object
         */
        function getHashParams() {
          var hashParams = {};
          var e, r = /([^&;=]+)=?([^&;]*)/g,
              q = window.location.hash.substring(1);
          while ( e = r.exec(q)) {
             hashParams[e[1]] = decodeURIComponent(e[2]);
          }
          return hashParams;
        }

        /**
         * Generates a random string containing numbers and letters
         * @param  {number} length The length of the string
         * @return {string} The generated string
         */
        function generateRandomString(length) {
          var text = '';
          var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

          for (var i = 0; i < length; i++) {
            text += possible.charAt(Math.floor(Math.random() * possible.length));
          }
          return text;
        };

        var userProfileSource = document.getElementById('user-profile-template').innerHTML,
            userProfileTemplate = Handlebars.compile(userProfileSource),
            userProfilePlaceholder = document.getElementById('user-profile');

            oauthSource = document.getElementById('oauth-template').innerHTML,
            oauthTemplate = Handlebars.compile(oauthSource),
            oauthPlaceholder = document.getElementById('oauth');

        var params = getHashParams();

        var access_token = params.access_token,
            state = params.state,
            storedState = localStorage.getItem(stateKey);

        if (access_token && (state == null || state !== storedState)) {
          alert('There was an error during the authentication');
        } else {
          localStorage.removeItem(stateKey);
          if (access_token) {
            $.ajax({
                url: 'https://api.spotify.com/v1/me',
                headers: {
                  'Authorization': 'Bearer ' + access_token
                },
                success: function(response) {
                  userProfilePlaceholder.innerHTML = userProfileTemplate(response);

                  $('#login').hide();
                  $('#loggedin').show();
                }
            });
          } else {
              $('#login').show();
              $('#loggedin').hide();
          }

          document.getElementById('login-button').addEventListener('click', function() {

            var client_id = 'CLIENT_ID'; // Your client id
            var redirect_uri = 'REDIRECT_URI'; // Your redirect uri

            var state = generateRandomString(16);

            localStorage.setItem(stateKey, state);
            var scope = 'user-read-private user-read-email';

            var url = 'https://accounts.spotify.com/authorize';
            url += '?response_type=token';
            url += '&client_id=' + encodeURIComponent(client_id);
            url += '&scope=' + encodeURIComponent(scope);
            url += '&redirect_uri=' + encodeURIComponent(redirect_uri);
            url += '&state=' + encodeURIComponent(state);

            window.location = url;
          }, false);
        }
      })();
    </script>
</html>


================================================
FILE: catalog-info.yaml
================================================
apiVersion: backstage.io/v1alpha1
kind: Component
metadata:
  name: web-api-auth-examples
spec:
  type: library
  owner: opx-partner-activation


================================================
FILE: get_user_profile/.gitignore
================================================
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
dist
dist-ssr
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?


================================================
FILE: get_user_profile/README.md
================================================

# Display your Spotify Profile Data in a Web App

This is the final code for the Spotify Web API - How to Display your Profile Data in a Web . You can run this demo directly or [walk through the tutorial](https://developer.spotify.com/documentation/web-api/howtos/web-app-profile).

## Pre-requisites

To run this demo you will need:

- A [Node.js LTS](https://nodejs.org/en/) environment or later.
- A [Spotify Developer Account](https://developer.spotify.com/)

## Usage

Create an app in your [Spotify Developer Dashboard](https://developer.spotify.com/dashboard/), set the redirect URI to ` http://localhost:5173/callback` and `http://localhost:5173/callback/` and copy your Client ID. 

Clone the repository, ensure that you are in the `get_user_profile` directory and run:

```bash
npm install
npm run dev
```

Replace the value for clientId in `/src/script.ts` with your own Client ID.


================================================
FILE: get_user_profile/index.html
================================================
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>Example</title>
  <script src="src/script.ts" type="module"></script>
</head>

<body>
  <h1>Display your Spotify Profile Data</h1>

  <section id="profile">
    <h2>Logged in as <span id="displayName"></span></h2>
    <img id="avatar" width="200" src="#" />
    <ul>
      <li>User ID: <span id="id"></span></li>
      <li>Email: <span id="email"></span></li>
      <li>Spotify URI: <a id="uri" href="#"></a></li>
      <li>Link: <a id="url" href="#"></a></li>
      <li>Profile Image: <span id="imgUrl"></span></li>
    </ul>
  </section>

</body>

</html>


================================================
FILE: get_user_profile/package.json
================================================
{
  "name": "vite-project",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "preview": "vite preview"
  },
  "devDependencies": {
    "typescript": "^4.9.3",
    "vite": "^4.0.0"
  }
}

================================================
FILE: get_user_profile/src/authCodeWithPkce.ts
================================================
export async function redirectToAuthCodeFlow(clientId: string) {
    const verifier = generateCodeVerifier(128);
    const challenge = await generateCodeChallenge(verifier);

    localStorage.setItem("verifier", verifier);

    const params = new URLSearchParams();
    params.append("client_id", clientId);
    params.append("response_type", "code");
    params.append("redirect_uri", "http://localhost:5173/callback");
    params.append("scope", "user-read-private user-read-email");
    params.append("code_challenge_method", "S256");
    params.append("code_challenge", challenge);

    document.location = `https://accounts.spotify.com/authorize?${params.toString()}`;
}

export async function getAccessToken(clientId: string, code: string) {
    const verifier = localStorage.getItem("verifier");

    const params = new URLSearchParams();
    params.append("client_id", clientId);
    params.append("grant_type", "authorization_code");
    params.append("code", code);
    params.append("redirect_uri", "http://localhost:5173/callback");
    params.append("code_verifier", verifier!);

    const result = await fetch("https://accounts.spotify.com/api/token", {
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body: params
    });

    const { access_token } = await result.json();
    return access_token;
}

function generateCodeVerifier(length: number) {
    let text = '';
    let possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

    for (let i = 0; i < length; i++) {
        text += possible.charAt(Math.floor(Math.random() * possible.length));
    }
    return text;
}

async function generateCodeChallenge(codeVerifier: string) {
    const data = new TextEncoder().encode(codeVerifier);
    const digest = await window.crypto.subtle.digest('SHA-256', data);
    return btoa(String.fromCharCode.apply(null, [...new Uint8Array(digest)]))
        .replace(/\+/g, '-')
        .replace(/\//g, '_')
        .replace(/=+$/, '');
}


================================================
FILE: get_user_profile/src/script.ts
================================================
// Because this is a literal single page application
// we detect a callback from Spotify by checking for the hash fragment
import { redirectToAuthCodeFlow, getAccessToken } from "./authCodeWithPkce";

const clientId = "your_client_id";
const params = new URLSearchParams(window.location.search);
const code = params.get("code");

if (!code) {
    redirectToAuthCodeFlow(clientId);
} else {
    const accessToken = await getAccessToken(clientId, code);
    const profile = await fetchProfile(accessToken);
    populateUI(profile);
}

async function fetchProfile(code: string): Promise<UserProfile> {
    const result = await fetch("https://api.spotify.com/v1/me", {
        method: "GET", headers: { Authorization: `Bearer ${code}` }
    });

    return await result.json();
}

function populateUI(profile: UserProfile) {
    document.getElementById("displayName")!.innerText = profile.display_name;
    document.getElementById("avatar")!.setAttribute("src", profile.images[0].url)
    document.getElementById("id")!.innerText = profile.id;
    document.getElementById("email")!.innerText = profile.email;
    document.getElementById("uri")!.innerText = profile.uri;
    document.getElementById("uri")!.setAttribute("href", profile.external_urls.spotify);
    document.getElementById("url")!.innerText = profile.href;
    document.getElementById("url")!.setAttribute("href", profile.href);
    document.getElementById("imgUrl")!.innerText = profile.images[0].url;
}


================================================
FILE: get_user_profile/src/types.d.ts
================================================
interface UserProfile {
    country: string;
    display_name: string;
    email: string;
    explicit_content: {
        filter_enabled: boolean,
        filter_locked: boolean
    },
    external_urls: { spotify: string; };
    followers: { href: string; total: number; };
    href: string;
    id: string;
    images: Image[];
    product: string;
    type: string;
    uri: string;
}

interface Image {
    url: string;
    height: number;
    width: number;
}


================================================
FILE: get_user_profile/tsconfig.json
================================================
{
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "module": "ESNext",
    "lib": ["ESNext", "DOM"],
    "moduleResolution": "Node",
    "strict": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "esModuleInterop": true,
    "noEmit": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "skipLibCheck": true
  },
  "include": ["src"]
}
Download .txt
gitextract_7i56fx55/

├── LICENSE
├── README.md
├── authorization/
│   ├── .gitignore
│   ├── authorization_code/
│   │   ├── README.md
│   │   ├── app.js
│   │   ├── package.json
│   │   └── public/
│   │       └── index.html
│   ├── authorization_code_pkce/
│   │   ├── README.md
│   │   ├── package.json
│   │   └── public/
│   │       ├── app.js
│   │       ├── index.html
│   │       └── style.css
│   ├── catalog-info.yaml
│   ├── client_credentials/
│   │   ├── README.md
│   │   └── app.js
│   └── implicit_grant/
│       ├── README.md
│       ├── app.js
│       ├── package.json
│       └── public/
│           └── index.html
├── catalog-info.yaml
└── get_user_profile/
    ├── .gitignore
    ├── README.md
    ├── index.html
    ├── package.json
    ├── src/
    │   ├── authCodeWithPkce.ts
    │   ├── script.ts
    │   └── types.d.ts
    └── tsconfig.json
Download .txt
SYMBOL INDEX (22 symbols across 5 files)

FILE: authorization/authorization_code_pkce/public/app.js
  method access_token (line 19) | get access_token() { return localStorage.getItem('access_token') || null; }
  method refresh_token (line 20) | get refresh_token() { return localStorage.getItem('refresh_token') || nu...
  method expires_in (line 21) | get expires_in() { return localStorage.getItem('refresh_in') || null }
  method expires (line 22) | get expires() { return localStorage.getItem('expires') || null }
  function redirectToSpotifyAuthorize (line 65) | async function redirectToSpotifyAuthorize() {
  function getToken (line 96) | async function getToken(code) {
  function refreshToken (line 116) | async function refreshToken() {
  function getUserData (line 132) | async function getUserData() {
  function loginWithSpotifyClick (line 142) | async function loginWithSpotifyClick() {
  function logoutClick (line 146) | async function logoutClick() {
  function refreshTokenClick (line 151) | async function refreshTokenClick() {
  function renderTemplate (line 158) | function renderTemplate(targetId, templateId, data = null) {

FILE: authorization/client_credentials/app.js
  function getToken (line 13) | async function getToken() {
  function getTrackInfo (line 28) | async function getTrackInfo(access_token) {

FILE: get_user_profile/src/authCodeWithPkce.ts
  function redirectToAuthCodeFlow (line 1) | async function redirectToAuthCodeFlow(clientId: string) {
  function getAccessToken (line 18) | async function getAccessToken(clientId: string, code: string) {
  function generateCodeVerifier (line 38) | function generateCodeVerifier(length: number) {
  function generateCodeChallenge (line 48) | async function generateCodeChallenge(codeVerifier: string) {

FILE: get_user_profile/src/script.ts
  function fetchProfile (line 17) | async function fetchProfile(code: string): Promise<UserProfile> {
  function populateUI (line 25) | function populateUI(profile: UserProfile) {

FILE: get_user_profile/src/types.d.ts
  type UserProfile (line 1) | interface UserProfile {
  type Image (line 19) | interface Image {
Condensed preview — 28 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (52K chars).
[
  {
    "path": "LICENSE",
    "chars": 11345,
    "preview": "                                 Apache License\n                           Version 2.0, January 2004\n                   "
  },
  {
    "path": "README.md",
    "chars": 385,
    "preview": "# Spotify Web API Examples\n\n## Contents\n\n- Authorization examples\n    - [Authorization Code]( /authorization/authorizati"
  },
  {
    "path": "authorization/.gitignore",
    "chars": 14,
    "preview": "node_modules/\n"
  },
  {
    "path": "authorization/authorization_code/README.md",
    "chars": 1017,
    "preview": "# Spotify Authorization Code example\n\nThis app displays your Spotify profile information using [Authorization Code](http"
  },
  {
    "path": "authorization/authorization_code/app.js",
    "chars": 4045,
    "preview": "/**\n * This is an example of a basic node.js script that performs\n * the Authorization Code oAuth2 flow to authenticate "
  },
  {
    "path": "authorization/authorization_code/package.json",
    "chars": 357,
    "preview": "{\n  \"name\": \"spotify-authorization-code-example\",\n  \"version\": \"0.0.2\",\n  \"description\": \"Spotify Authorization Code flo"
  },
  {
    "path": "authorization/authorization_code/public/index.html",
    "chars": 4829,
    "preview": "<!doctype html>\n<html>\n  <head>\n    <title>Example of the Authorization Code flow with Spotify</title>\n    <link rel=\"st"
  },
  {
    "path": "authorization/authorization_code_pkce/README.md",
    "chars": 813,
    "preview": "# Spotify Authorization Code with PKCE example\n\nThis app displays your Spotify profile information using [Authorization "
  },
  {
    "path": "authorization/authorization_code_pkce/package.json",
    "chars": 291,
    "preview": "{\n  \"name\": \"spotify-authorization-code-pkce\",\n  \"version\": \"1.0.0\",\n  \"description\": \"Spotify Authorization Code with P"
  },
  {
    "path": "authorization/authorization_code_pkce/public/app.js",
    "chars": 6258,
    "preview": "/**\n * This is an example of a basic node.js script that performs\n * the Authorization Code with PKCE oAuth2 flow to aut"
  },
  {
    "path": "authorization/authorization_code_pkce/public/index.html",
    "chars": 2099,
    "preview": "<!DOCTYPE html>\n<html>\n\n<head>\n  <title>Example of the Authorization Code with PKCE flow with Spotify</title>\n  <link re"
  },
  {
    "path": "authorization/authorization_code_pkce/public/style.css",
    "chars": 604,
    "preview": "body {\n    margin: 1rem;\n    font-family: Arial, Helvetica, sans-serif;\n}\n\ntr:nth-child(even) {\n    background-color: #e"
  },
  {
    "path": "authorization/catalog-info.yaml",
    "chars": 144,
    "preview": "apiVersion: backstage.io/v1alpha1\nkind: Component\nmetadata:\n  name: web-api-auth-examples\nspec:\n  type: library\n  owner:"
  },
  {
    "path": "authorization/client_credentials/README.md",
    "chars": 898,
    "preview": "# Spotify Client Credentials example\n\nThis app retrieves information from an artist's track using [Client Credentials](h"
  },
  {
    "path": "authorization/client_credentials/app.js",
    "chars": 1165,
    "preview": "/**\n * This is an example of a basic node.js script that performs\n * the Client Credentials oAuth2 flow to authenticate "
  },
  {
    "path": "authorization/implicit_grant/README.md",
    "chars": 1234,
    "preview": "# Spotify Implicit Grant example\n\nThis app displays your Spotify profile information using [Implicit Grant](https://deve"
  },
  {
    "path": "authorization/implicit_grant/app.js",
    "chars": 453,
    "preview": "/**\n * This is an example of a basic node.js script that performs\n * the Implicit Grant oAuth2 flow to authenticate agai"
  },
  {
    "path": "authorization/implicit_grant/package.json",
    "chars": 239,
    "preview": "{\n  \"name\": \"spotify-implicit-grant-example\",\n  \"version\": \"0.0.2\",\n  \"description\": \"Spotify Implicit Grant example\",\n "
  },
  {
    "path": "authorization/implicit_grant/public/index.html",
    "chars": 5368,
    "preview": "<!doctype html>\n<html>\n  <head>\n    <title>Example of the Implicit Grant flow with Spotify</title>\n    <link rel=\"styles"
  },
  {
    "path": "catalog-info.yaml",
    "chars": 144,
    "preview": "apiVersion: backstage.io/v1alpha1\nkind: Component\nmetadata:\n  name: web-api-auth-examples\nspec:\n  type: library\n  owner:"
  },
  {
    "path": "get_user_profile/.gitignore",
    "chars": 253,
    "preview": "# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\npnpm-debug.log*\nlerna-debug.log*\n\nnode_modules\ndist\ndis"
  },
  {
    "path": "get_user_profile/README.md",
    "chars": 894,
    "preview": "\n# Display your Spotify Profile Data in a Web App\n\nThis is the final code for the Spotify Web API - How to Display your "
  },
  {
    "path": "get_user_profile/index.html",
    "chars": 633,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n  <meta charset=\"utf-8\">\n  <title>Example</title>\n  <script src=\"src/script.ts\""
  },
  {
    "path": "get_user_profile/package.json",
    "chars": 269,
    "preview": "{\n  \"name\": \"vite-project\",\n  \"private\": true,\n  \"version\": \"0.0.0\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"dev\": \"vite"
  },
  {
    "path": "get_user_profile/src/authCodeWithPkce.ts",
    "chars": 2026,
    "preview": "export async function redirectToAuthCodeFlow(clientId: string) {\n    const verifier = generateCodeVerifier(128);\n    con"
  },
  {
    "path": "get_user_profile/src/script.ts",
    "chars": 1466,
    "preview": "// Because this is a literal single page application\n// we detect a callback from Spotify by checking for the hash fragm"
  },
  {
    "path": "get_user_profile/src/types.d.ts",
    "chars": 465,
    "preview": "interface UserProfile {\n    country: string;\n    display_name: string;\n    email: string;\n    explicit_content: {\n      "
  },
  {
    "path": "get_user_profile/tsconfig.json",
    "chars": 445,
    "preview": "{\n  \"compilerOptions\": {\n    \"target\": \"ESNext\",\n    \"useDefineForClassFields\": true,\n    \"module\": \"ESNext\",\n    \"lib\":"
  }
]

About this extraction

This page contains the full source code of the spotify/web-api-auth-examples GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 28 files (47.0 KB), approximately 11.8k tokens, and a symbol index with 22 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!