Giter VIP home page Giter VIP logo

web-api-examples's Introduction

web-api-examples's People

Contributors

alnacle avatar bombasticman avatar dijonkitchen avatar hughrawlinson avatar jmperez avatar mikhailusov avatar perploug avatar pomle avatar thelinmichael avatar thisisjofrank avatar woodahs avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

web-api-examples's Issues

Error - INVALID_CLIENT: Invalid redirect URI

Hi, I'm currently going through the Spotify Web API tutorial. I have set up everything and then tried to run the application. I am able to get to Login Link, but then after I login I am redirected to a page with the error "INVALID_CLIENT: Invalid redirect URI". I have set up my application on My Dashboard and created the redirect URI: "http://spotifysentiment.com/callback/". However, after setting my redirect_uri to 'http://spotifysentiment.com/callback' in app.js I still get the same error. Am I doing something wrong?

Error: Cannot find module 'express'

Hi , some one can help please ?
Thanks .

`` Node.js v18.6.0

C:\Users\Jony\web-api-auth-examples\authorization_code>node app.js
node:internal/modules/cjs/loader:959
throw err;
^

Error: Cannot find module 'express'
Require stack:

  • C:\Users\Jony\web-api-auth-examples\authorization_code\app.js
    ←[90m at Module._resolveFilename (node:internal/modules/cjs/loader:956:15)←[39m
    ←[90m at Module._load (node:internal/modules/cjs/loader:804:27)←[39m
    ←[90m at Module.require (node:internal/modules/cjs/loader:1022:19)←[39m
    ←[90m at require (node:internal/modules/cjs/helpers:102:18)←[39m
    at Object. ←[90m(C:\Users\Jony\web-api-auth-examples\authorization_code\←[39mapp.js:10:15←[90m)←[39m
    ←[90m at Module._compile (node:internal/modules/cjs/loader:1120:14)←[39m
    ←[90m at Module._extensions..js (node:internal/modules/cjs/loader:1174:10)←[39m
    ←[90m at Module.load (node:internal/modules/cjs/loader:998:32)←[39m
    ←[90m at Module._load (node:internal/modules/cjs/loader:839:12)←[39m
    ←[90m at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)←[39m {
    code: ←[32m'MODULE_NOT_FOUND'←[39m,
    requireStack: [
    ←[32m'C:\Users\Jony\web-api-auth-examples\authorization_code\app.js'←[39m
    ]
    }

``

Handlebars is not Defined

I am going through the web-api tutorial and just hit a snag. I was able to fix it, but other users may have the same error.

At the "Prompting the User to Login" step, I got some errors (and a blank page) when I opened index.html. In the console, it said that the Bootstrap and Handlebars (CDN) files could not be found.

I was able to fix this by adding the "https:" to the beginning of the url in each link href (see below), whereas there was only the "//". Jquery already had an http:, so no error.

Like I said, I was able to fix it, but you might want to change the code here or add a note in the tutorial.

<link rel="stylesheet" href="**https:**//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">

<script src="**https:**//cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0-alpha.1/handlebars.min.js"></script>

Thanks!
Max

Missing required parameter: client_id

Hi!

I'm facing an issue that I don't understand!
I am developing a react-native (js) app which try to access Spotify api using the Implicit Grant Flow.

Here is my method to get the access token:

async function getTokenFromAPI() {
    try {
        var params = {
            client_id: '<client_id>',
            response_type: 'token',
            redirect_uri: 'http://localhost:8888/callback'
        };

        var esc = encodeURIComponent;
        var query = Object.keys(params)
            .map(k => `${esc(k)}=${esc(params[k])}`)
            .join('&');

        fetch('https://accounts.spotify.com/authorize', query).then(function (response) {
            console.log('response, ' + JSON.stringify(response));
            return response;
        })
    } catch(error) {
        console.error(error);
    }
}

but It answers that:
Missing required parameter: client_id

I also used Postman to check if my request is good and I get the same response...

Is there something wrong? On their doc they tell that it is a GET method with only 3 parameters..

Thank you in advance for any workaround!

[Closed]Hmmm, i do somethink wrong?

C:\Users\Ningaro\Documents\GitHub\web-api-auth-examples-master\authorization_code>powershell -file powshell.ps1
module.js:557
    throw err;
    ^

Error: Cannot find module 'express'
    at Function.Module._resolveFilename (module.js:555:15)
    at Function.Module._load (module.js:482:25)
    at Module.require (module.js:604:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (C:\Users\Ningaro\Documents\GitHub\web-api-auth-examples-master\authorization_code\app.js:10:15)
    at Module._compile (module.js:660:30)
    at Object.Module._extensions..js (module.js:671:10)
    at Module.load (module.js:573:32)
    at tryModuleLoad (module.js:513:12)
    at Function.Module._load (module.js:505:3)

Windows 10 x64
Node.JS 9.4.0

Cannot find module 'express'

I already tried using npm install and it still doesn't work.


/**
 * 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/web-api/authorization-guide/#authorization_code_flow
 */
 config=require("./config.json")
 var express = require('express'); // Express web server framework
 var request = require('request'); // "Request" library
 var cors = require('cors');
 var querystring = require('querystring');
 var cookieParser = require('cookie-parser');
 var client_id = config.CLIENT_ID; // Your client id
 var client_secret = config.CLIENT_SECRET; // Your secret
 var redirect_uri = config.REDIRECT_URI; // Your redirect uri
 
 /**
  * Generates a random string containing numbers and letters
  * @param  {number} length The length of the string
  * @return {string} The generated string
  */
 var generateRandomString = function(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 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: {
         'Authorization': 'Basic ' + (new Buffer(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) {
 
   // requesting access token from refresh token
   var refresh_token = req.query.refresh_token;
   var authOptions = {
     url: 'https://accounts.spotify.com/api/token',
     headers: { 'Authorization': 'Basic ' + (new Buffer(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;
       res.send({
         'access_token': access_token
       });
     }
   });
 });
 
 console.log('Listening on 8888');
 app.listen(8888);

OUTPUT

node:internal/modules/cjs/loader:936
  throw err;
  ^
Error: Cannot find module 'express'
Require stack:
- d:\Coding\Spotify\generate.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (d:\Coding\Spotify\generate.js:11:16)
    at Module._compile (node:internal/modules/cjs/loader:1105:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [ 'd:\\Coding\\Spotify\\generate.js' ]
}

Authorization: Query parameter 'state' not protecting against attackers

According to the Authorization code flow (link), on
GET https://accounts.spotify.com/authorize
the query parameter state can be used to protect against cross-site request forgery. I however don't see how the implementation in the web example gives any extra security against attackers.

In the file web-api-auth-examples/authorization_code/app.js (link), following code is implemented:

app.get('/callback', function(req, res) {
    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) {
        // Complain about mismatch
    }
    // ...
}

Both variables state and storedState are provided by the client, so an attacker could just make up an arbitrary cookie and state that matches. I agree that it would prevent gaining access by mistake, if the query link is shared. It does however not provide any security against attackers as stated in the documentation.

Feel free to correct if I am wrong!

Add example for Authorization + PKCE code flow

I noticed that these web API auth examples do not include an Authorization + PKCE code flow example. Adding this example would be helpful so people can easily implement PKCE in applications created with the Spotify web API.

Error - 'Something' went wrong

I'm having a hard time trying to authenticate my spotify app on localhost. I have my redirect_uri set as localhost:8888/callback (have also tried it with http://)at my developer account, but I get this error page when terminal prompts me to enter the URL I'm being redirected to.

I am running my server using python -m SimpleHTTPServer 8888, and entering at terminal python script.py username.

this is my python script:

scope = 'user-library-read'

if len(sys.argv) > 1:
    username = sys.argv[1]
else:
    print "Usage: %s username" % (sys.argv[0],)
    sys.exit()

token = util.prompt_for_user_token(username, scope, client_id='myId', client_secret='mySecret', **redirect_uri='localhost:8888/callback'**)

if token:
    sp = spotipy.Spotify(auth=token)
    results = sp.current_user_saved_tracks()
    for item in results['items']:
        track = item['track']
        print track['name'] + ' - ' + track['artists'][0]['name']
else:
    print "Can't get token for", username

what could be wrong? please help

npm install throwing error "Cannot find module 'yallist'"

I tried installing inside the folder "web-api-auth-examples-master" & sub folders bt same error...have install node.js successfully...

\web-api-auth-examples-master> npm install
node:internal/modules/cjs/loader:933
const err = new Error(message);
^

Error: Cannot find module 'yallist'
Require stack:

  • C:\Users\This pc\AppData\Roaming\npm\node_modules\npm\node_modules\lru-cache\index.js
  • C:\Users\This pc\AppData\Roaming\npm\node_modules\npm\node_modules\semver\classes\range.js
  • C:\Users\This pc\AppData\Roaming\npm\node_modules\npm\node_modules\semver\classes\comparator.js
  • C:\Users\This pc\AppData\Roaming\npm\node_modules\npm\node_modules\semver\index.js
  • C:\Users\This pc\AppData\Roaming\npm\node_modules\npm\lib\utils\unsupported.js
  • C:\Users\This pc\AppData\Roaming\npm\node_modules\npm\lib\cli.js
  • C:\Users\This pc\AppData\Roaming\npm\node_modules\npm\bin\npm-cli.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object. (C:\Users\This pc\AppData\Roaming\npm\node_modules\npm\node_modules\lru-cache\index.js:4:17)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.require (node:internal/modules/cjs/loader:1005:19) {
    code: 'MODULE_NOT_FOUND',
    requireStack: [
    'C:\Users\This pc\AppData\Roaming\npm\node_modules\npm\node_modules\lru-cache\index.js',
    'C:\Users\This pc\AppData\Roaming\npm\node_modules\npm\node_modules\semver\classes\range.js',
    'C:\Users\This pc\AppData\Roaming\npm\node_modules\npm\node_modules\semver\classes\comparator.js',
    'C:\Users\This pc\AppData\Roaming\npm\node_modules\npm\node_modules\semver\index.js',
    'C:\Users\This pc\AppData\Roaming\npm\node_modules\npm\lib\utils\unsupported.js',
    'C:\Users\This pc\AppData\Roaming\npm\node_modules\npm\lib\cli.js',
    'C:\Users\This pc\AppData\Roaming\npm\node_modules\npm\bin\npm-cli.js'
    ]
    }

{ error: 'invalid_client' } }

I get invalid client even if I have my client and secret inputted correctly. I am trying the client example.

No idea what I am doing wrong here. Note: I changed Buffer() to Buffer.from.


`
var request = require('request'); // "Request" library

var client_id = 'x'; // Your client id
var client_secret = 'x'; // Your secret

// your application requests authorization

var authOptions = {
  url: 'https://accounts.spotify.com/api/token',
  headers: {
    'Authorization': 'Basic ' + Buffer.from((client_id + ':' + client_secret).toString('base64'))
  },
  form: {
    grant_type: 'client_credentials',
  },
  json: true
};

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

    // use the access token to access the Spotify Web API
    var token = body.access_token;
    var options = {
      url: 'https://api.spotify.com/v1/users/jmperezperez',
      headers: {
        'Authorization': 'Bearer ' + token
      },
      json: true
    };
    request.get(options, function(error, response, body) {
      console.log(body);
    });
  }
});

request.post(authOptions);`

Showing the user their playlist

I want to be able to add the scope I put in to be able to show back to the user, any suggestion? I am guessing I need to get it in the .html file, but not sure how to format it.
<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>

CORS not working here

Server gets user information.
Client request gets rejected: "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.spotify.com/v1/me. (Reason: CORS request did not succeed)."

I don't know how to fix this.

BR

client credentials not working for "https://api.spotify.com/v1/me/" endpoint

I am trying to get the song that is currently playing on my player, using the 'client credentials'. However, when using the sample code, a "username invalid" error is returned. I've tried with several other endpoints related to what was mentioned in the title, and they all return the same error.

How to proceed?

Note: I'm using NodeJS

Accessing me/top/tracks

My apologies if this isn't the correct venue for discussion; feel free to direct me to such a thing! Thank you for this repo- I'm trying to wrap my head around how to access the "me" side of things, which this somewhat explains. How can I query 'me/top/tracks'? Really struggling with this.

Regards,
Aaron

It Comes like this when i try to create my first music discord bot

internal/modules/cjs/loader.js:883
throw err;
^

Error: Cannot find module 'lava-spotify'
Require stack:

  • C:\Users\T460\Downloads\Dhruva\Disc Bots\lavalink-musicbot-master\src\structures\MusicClient.js
  • C:\Users\T460\Downloads\Dhruva\Disc Bots\lavalink-musicbot-master\src\bot.js
  • C:\Users\T460\Downloads\Dhruva\Disc Bots\lavalink-musicbot-master\index.js

Using Spotify API in R

Hello, I'm beginning to use R and I'd like to use Spotify's API. There aren't many tutorials out there so I've had some issues. I've followed along but I'm receiving the error "INVALID_CLIENT: Invalid redirect URI" and also being prompted to enter an authorization code in Rstudio.

So far, this is what I've used.

install.packages('Rspotify')
install.packages('httr')
library(Rspotify)
library(devtools)
library(tidyr)
library(knitr)

Sys.setenv(SPOTIFY_CLIENT_ID = 'f51c0ad8ef9a4c0aabeb303527d39e1a')
Sys.setenv(SPOTIFY_CLIENT_SECRET = '4f9972f7dd23444dafbd747e9deb316f')

spotifyOAuth(app_id="xxxx", client_id = 'f51c0ad8ef9a4c0aabeb303527d39e1a',
client_secret = '4f9972f7dd23444dafbd747e9deb316f')

I then receive this output
The downloaded binary packages are in
/var/folders/cj/m1k376r93wlf7n_vr61t4cch0000gn/T//RtmpP4hrDI/downloaded_packages

library(Rspotify)
library(devtools)
Loading required package: usethis
library(tidyr)
library(knitr)

Sys.setenv(SPOTIFY_CLIENT_ID = 'f51c0ad8ef9a4c0aabeb303527d39e1a')
Sys.setenv(SPOTIFY_CLIENT_SECRET = '4f9972f7dd23444dafbd747e9deb316f')

spotifyOAuth(app_id="xxxx", client_id = 'f51c0ad8ef9a4c0aabeb303527d39e1a',

  •          client_secret = '4f9972f7dd23444dafbd747e9deb316f')
    

httpuv not installed, defaulting to out-of-band authentication
Enter authorization code: ___

I'm not sure where to get this authorization code from

Invalid redirect URI

I have set my redirect URI do be http://localhost:8888/callback/ in the Spotify dashboard for my app and set the redirect_uri variable to http://localhost:8888/callback in the example, but as soon as I visit http://localhost:8888/login an empty browser window is displayed with the following message : INVALID_CLIENT: Invalid redirect URI and the url in the address bar is as follows : https://accounts.spotify.com/authorize?response_type=code&client_id=40e1d1267f2d447189fdc004f7d5aa1e&scope=user-read-email&redirect_uri=http%3A%2F%2Flocalhost%3A8888%2Fcallback&state=IlvEOLr81HceC2TB

Am I doing anything wrong, or are these examples no longer valid?

Thanks in advance for any advice you can give!

No maintenance of this repo? Please check pull requests

Hi all,

@JMPerez @thelinmichael

Thanks for the great work you've done providing this repo however it would be nice that it gets checked on from time to time. There are many great pending pull requests to update these examples to be in line with what's being done post 2020 like PR #45 (fixes many deprecations etc). I understand that this repo is low priority but it is the number one hit for spotify web auth examples on Google.

If this repo is deprecated or not maintained anymore, please state so in the readme and link to an active or maintained fork like in PR #45.

/login not found (node js rookie)

I have a server on Digital Ocean that I've uploaded the index.HTML and app.js files to. I run "node app.js" through putty and get "Listening on 8888". I go to my domain, click the button "log in with spotify" and get the error "the requested URL /login was not found on this server."

I suspect the issue is pretty basic seeing as I have no experience with nodejs, can someone point me in the right direction? My Google skills aren't helping me.

DeprecationWarning: Buffer()

When running the API example linked in the docs, there is a deprecation warning being logged.

[DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.

Just thought I would point this out, perhaps the API auth example should be updated!

Thanks!

Content Security Policy (CSP) violation when opening Spotify login URL

I followed Web API tutorial for Authorization Code Flow, provided the application ID, secret and redirect URI.
I'm getting this CSP violation error in browser console:

Refused to load the script 'data:application/javascript;base64,dmFyIHVyY2hpblRyYWNrZXI9...' because it violates the following Content Security Policy directive: "script-src 'self' https://www.google-analytics.com https://ssl.google-analytics.com https://www.google.com https://www.gstatic.com/recaptcha/ https://www.google.com/recaptcha/ https://accounts.scdn.co". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

index.html syntax error, loads strangely

I have followed the Web API Tutorial up to running node app.js, where the page fails to load properly. All that appears is an ellipsis on a white screen.

I took a look at the html.index, and evidently the two occurrences of ellipses cause the issue.
index html code

By playing around it seems like the first "..." produces the visible "..." in the browser, while the second "..." has no visible effect.

How can I get the page load properly? (As below)

Web API quickstart guide no longer works

Following the quickstart in https://developer.spotify.com/documentation/web-api/quick-start/ using the example authorization code no longer works.

After filling in client id and secret as needed and setting the redirect uri to 'http://localhost:8888/callback' as indicated by the guide, clicking the "Log in with Spotify" button, produces the following error:
INVALID_CLIENT: Invalid redirect URI.

I've tried replacing it with https://example.com/callback from https://developer.spotify.com/documentation/general/guides/authorization-guide/#authorization-code-flow to test that the actual authorization code works if a correct redirect URI is supplied, and it appears that it does, but obviously the rest of the quickstart guide (displaying the /me info) doesn't work.

Please update the quickstart guide to use a different redirect URI (or update the code to ship with a working example uri) or update the guide itself if this type of redirect is no longer allowed.

INVALID_CLIENT: Invalid redirect URI

Hi,

This is probably a very stupid issue but I have fetched the code, updated app.js client_id, client_secret and redirect_uri

var client_id = 'my client id'; // Your client id
var client_secret = 'my secret'; // Your secret
var redirect_uri = 'http://localhost:8888/callback'; // Your redirect uri

Starting the app in the folder where app.js is located:

:~/Development/Spotify/web-api-auth-examples/authorization_code$ nodejs app.js
Listening on 8888

(Note that it is not node since I am running Ubuntu and there it is nodejs.)
startpage

When pressing the "Log in with Spotify" button I get this:
ivalid_client_issue

I have made a wireshark log during the transaction but can't make anything out of it.

In another issue was the question raised to test that the server is listening to that redirect_uri which here comes up as:
state_mismatch

and running curl:
:~$ curl http://localhost:8888/callback
Found. Redirecting to /#error=state_mismatch

Any ideas?

authentication_code example throwing mismatch error

Hi there, I've recently decided to start tinkering with the spotify api to see just what i can do with it. However I can't seem to get past the authentication phase...(T_T). Through some searching I've found that the redirect_uri is the most common fault. and through reading the code, it would seem the message is only thrown when the state and the storedstate aren't equivalent, or if the state is null. Now I've combed through the possible typo's of the redirect_uri, on both the app.js code file and the spotify dashboard for whitelisting the uri address, however none of them are working. Is anyone else experiencing this issue still? I don't know if it matters but im running this on linux 18.04.4 LTS (Bionic Beaver)
screen
screen2

Question about Authorization flow

Hi guys, I have deployed my node/express server on Heroku and my create-react-app on netlify. The end goal I am trying to achieve here is to have a seemless transition between each access token expiring. Right now when I am listening on my app, after 1 hour the access token expires and I have to manually refresh the page to login again. As per the documentation, it is possible to extend a session by hitting the /refresh route if you already have a refresh token and your secret credentials. The part I am not understanding is the granular details of the response.redirects

https://github.com/hollowic/music-player-backend/blob/42ce542f6bc6c1ba00f429370071b08dbea46ba9/server.js#L104

When I send an AJAX request, it seems to be blocked here and I am not experienced enough with node/express nor oauth to understand what this redirect really entails. I tried to rewrite it using an axios.get request but that didn't seem to get me anywhere

I was wondering if it was possible to have the heroku app send the new access token to the front end, before each old access token expired since I seem to get CORS errors when I try to do an AJAX request from netlify. And how would that look like?

Thank you so much for taking the time to read my question.

[About version #45] How to get the data printed in the console, like in master version?

Working with pull #45 and I want to get the data printed in json format in the console, just like it's done in master. I understand that it's done by console.log(response.data); but it returns
{ access_token: 'blah blah blah', token_type: 'Bearer', expires_in: 3600, refresh_token: 'blah blah blah', scope: 'playlist-read-private user-read-email user-read-private' }

so I'm probably writing the console.log in the wrong place, but I can't figure out where I should. Any help?

how to deploy the authorization code for creating websites

please help me..🚧🚧

  • I am willing to deploy the authorization_code files.
  • I have created an Application on react.js -- for client
  • and used the authorization _code for the user's login .
  • now i don't know how to deploy the work...

Need help

when I do a node auth.js this pops up

internal/modules/cjs/loader.js:1023
throw err;
^

Error: Cannot find module '/Users/tireejackson/Documents/backend_repo/auth.js'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:1020:15)
at Function.Module._load (internal/modules/cjs/loader.js:890:27)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47 {
code: 'MODULE_NOT_FOUND',
requireStack: []
}

Unhandled Rejection (TypeError): Cannot read property 'name' of undefined

Hi folks,

Trying to follow this tutorial: https://www.youtube.com/watch?v=prayNyuN3w0 using this web api. I'm having an issue where my response after calling getMyCurrentPlaybackState(). All of the authorization stuff is working. Here is the code:

import React, { Component } from 'react';
import P5Wrapper from 'react-p5-wrapper';
import sketch from './sketch';

import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import Button from 'react-bootstrap/Button';

import Spotify from 'spotify-web-api-js';

const spotifyWebAPI = new Spotify();

export default class App extends Component {
  constructor(props) {
    super(props);
    const params = this.getHashParams();
    this.state = {
      loggedIn: params.access_token ? true: false,
      nowPlaying: {
        name: "Not Checked",
        image: ""
      }
    }
    if(params.access_token) {
      spotifyWebAPI.setAccessToken(params.access_token);
    }
  }

  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;
  }

  getNowPlaying() {
    spotifyWebAPI.getMyCurrentPlaybackState()
      .then((response) => {
        this.setState({
          nowPlaying: {
            name: response.item.name,
            image: response.item.album.images[0]
          }
        })
      })
  }

  render() {
      return (
        <div className="App">
          <h1>Spotify Visualizer</h1>

          <Button variant="success" size="lg" href="http://localhost:8888">Login With Spotify</Button>

          <div>
            Now Playing: {this.state.nowPlaying.name}
          </div>

          <div>
            <img src={this.state.nowPlaying.image} style={{width: "100px"}}/>
          </div>

          <Button variant="outline-success" onClick={() => this.getNowPlaying()}>Currently Playing</Button>
        </div>
      );
  }
}

Any help would be greatly appreciated!

Authorization flow issue

Hi, I cannot login to spotify using Authorization flow. This is my code `
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
}));

});` Could sonebody help me please?

Front-end Auth Flow

Hi, tried to implement Implicit grant flow in simple Create React App. Ending with CORS issues. Can you clarify me, how should I implement your Auth Flows client-side. Can't find anything about this, but only issues this CORS from other users.

Here is my request:

const res = await axios.get(
        'https://accounts.spotify.com/authorize',
        {
          headers: {'Content-Type': 'application/json'},
          params: {
            client_id: process.env.REACT_APP_SPOTIFY_CLIENT_ID,
            response_type: 'token',
            redirect_uri: process.env.REACT_APP_APPLICATION_URL,
            scopes: 'playlist-modify-public%20playlist-modify-private%20playlist-read-private'
          }
        }
    );

Thank you.

Error: Cannot find module 'express'

When I try to run node app.js, I get the error message:

Error: Cannot find module 'express' at Function.Module._resolveFilename (internal/modules/cjs/loader.js:580:15) at Function.Module._load (internal/modules/cjs/loader.js:506:25) at Module.require (internal/modules/cjs/loader.js:636:17) at require (internal/modules/cjs/helpers.js:20:18) at Object.<anonymous> (C:\Users\MyUsername\Documents\njtest\spotifyapi\web-api-auth-examples-master\web-api-auth-examples-master\authorization_code\app.js:10:15) at Module._compile (internal/modules/cjs/loader.js:688:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10) at Module.load (internal/modules/cjs/loader.js:598:32) at tryModuleLoad (internal/modules/cjs/loader.js:537:12) at Function.Module._load (internal/modules/cjs/loader.js:529:3)

Is this on my end or did something happen here?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.