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
================================================
Example of the Authorization Code flow with Spotify
================================================
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
================================================
Example of the Authorization Code with PKCE flow with Spotify
Welcome to the OAuth2 PKCE Example
Logged in as
Display name
Id
Email
Spotify URI
Link
Profile Image
Country
oAuth info
Access token
Refresh token
Expiration at
${getExpirationDate(expires_in)}
================================================
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
================================================
Example of the Implicit Grant flow with Spotify
This is an example of the Implicit Grant flow
================================================
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
================================================
Example