OAuth2 fails to return auth token using simple-oauth2 and Firebase Functions for Spotify Authentication












0















I have been working on a oauth2 flow for spotify by following this similar tutorial by the Firebase team for Instagram HERE



I am able to submit my credentials and return the user code and state in the url, but when I run the method to submit the code to return an auth token, the auth token that I print to console in the Firebase functions returns: Auth Token Error Not Found. Here's my workflow:



Here's the Spotify docs



FIRST, I have a function to configure my spotifyOAuth:



function spotifyOAuth2Client() {
// Spotify OAuth 2 setup
const credentials = {
client: {
id: functions.config().spotify.clientid,
secret: functions.config().spotify.clientsecret,
},
auth: {
tokenHost: 'https://accounts.spotify.com',
authorizePath: '/authorize'
},
};
return require('simple-oauth2').create(credentials);
}


I use that function in this Firebase function that is called using https://us-central1-<my project string>.cloudfunctions.net/redirect:



exports.redirect = functions.https.onRequest((req, res) => {
const oauth2 = spotifyOAuth2Client();

cookieParser()(req, res, () => {
const state = req.cookies.state || crypto.randomBytes(20).toString('hex');
console.log('Setting verification state:', state);
res.cookie('state', state.toString(), {
maxAge: 3600000,
secure: true,
httpOnly: true,
});
const redirectUri = oauth2.authorizationCode.authorizeURL({
redirect_uri: OAUTH_REDIRECT_URI,
//scope: OAUTH_SCOPES,
state: state,
});
console.log('Redirecting to:', redirectUri);
res.redirect(redirectUri);
});
});


The code above returns a url string with the proper parameters, the following code block is where my code breaks, I have another cloud function that runs after being redirected from the res.redirect(redirectUri) above. And when I try to run the getToken() method, it appears to not return anything because I hit the catch block instead? This is where I observe the Auth Token Error Not Found.



const oauth2 = spotifyOAuth2Client();

try {
return cookieParser()(req, res, async () => {
console.log('Received verification state:', req.cookies.state);
console.log('Received state:', req.query.state);
if (!req.cookies.state) {
throw new Error('State cookie not set or expired. Maybe you took too long to authorize. Please try again.');
} else if (req.cookies.state !== req.query.state) {
throw new Error('State validation failed');
}
console.log('Received auth code:', req.query.code);
console.log(OAUTH_REDIRECT_URI);

// Get the access token object (the authorization code is given from the previous step).
const tokenConfig = {
code: req.query.code,
redirect_uri: 'http://localhost:8100/popup'
};

// Save the access token
try {
const result = await oauth2.authorizationCode.getToken(tokenConfig)
const accessToken = oauth2.accessToken.create(result);
console.log('inside try');
console.log(result);
console.log(accessToken);
} catch (error) {
console.log('Access Token Error', error.message);
}


I've double checked my spotify client/secret credentials in the config, what is going wrong with this OAuth2 flow?










share|improve this question



























    0















    I have been working on a oauth2 flow for spotify by following this similar tutorial by the Firebase team for Instagram HERE



    I am able to submit my credentials and return the user code and state in the url, but when I run the method to submit the code to return an auth token, the auth token that I print to console in the Firebase functions returns: Auth Token Error Not Found. Here's my workflow:



    Here's the Spotify docs



    FIRST, I have a function to configure my spotifyOAuth:



    function spotifyOAuth2Client() {
    // Spotify OAuth 2 setup
    const credentials = {
    client: {
    id: functions.config().spotify.clientid,
    secret: functions.config().spotify.clientsecret,
    },
    auth: {
    tokenHost: 'https://accounts.spotify.com',
    authorizePath: '/authorize'
    },
    };
    return require('simple-oauth2').create(credentials);
    }


    I use that function in this Firebase function that is called using https://us-central1-<my project string>.cloudfunctions.net/redirect:



    exports.redirect = functions.https.onRequest((req, res) => {
    const oauth2 = spotifyOAuth2Client();

    cookieParser()(req, res, () => {
    const state = req.cookies.state || crypto.randomBytes(20).toString('hex');
    console.log('Setting verification state:', state);
    res.cookie('state', state.toString(), {
    maxAge: 3600000,
    secure: true,
    httpOnly: true,
    });
    const redirectUri = oauth2.authorizationCode.authorizeURL({
    redirect_uri: OAUTH_REDIRECT_URI,
    //scope: OAUTH_SCOPES,
    state: state,
    });
    console.log('Redirecting to:', redirectUri);
    res.redirect(redirectUri);
    });
    });


    The code above returns a url string with the proper parameters, the following code block is where my code breaks, I have another cloud function that runs after being redirected from the res.redirect(redirectUri) above. And when I try to run the getToken() method, it appears to not return anything because I hit the catch block instead? This is where I observe the Auth Token Error Not Found.



    const oauth2 = spotifyOAuth2Client();

    try {
    return cookieParser()(req, res, async () => {
    console.log('Received verification state:', req.cookies.state);
    console.log('Received state:', req.query.state);
    if (!req.cookies.state) {
    throw new Error('State cookie not set or expired. Maybe you took too long to authorize. Please try again.');
    } else if (req.cookies.state !== req.query.state) {
    throw new Error('State validation failed');
    }
    console.log('Received auth code:', req.query.code);
    console.log(OAUTH_REDIRECT_URI);

    // Get the access token object (the authorization code is given from the previous step).
    const tokenConfig = {
    code: req.query.code,
    redirect_uri: 'http://localhost:8100/popup'
    };

    // Save the access token
    try {
    const result = await oauth2.authorizationCode.getToken(tokenConfig)
    const accessToken = oauth2.accessToken.create(result);
    console.log('inside try');
    console.log(result);
    console.log(accessToken);
    } catch (error) {
    console.log('Access Token Error', error.message);
    }


    I've double checked my spotify client/secret credentials in the config, what is going wrong with this OAuth2 flow?










    share|improve this question

























      0












      0








      0








      I have been working on a oauth2 flow for spotify by following this similar tutorial by the Firebase team for Instagram HERE



      I am able to submit my credentials and return the user code and state in the url, but when I run the method to submit the code to return an auth token, the auth token that I print to console in the Firebase functions returns: Auth Token Error Not Found. Here's my workflow:



      Here's the Spotify docs



      FIRST, I have a function to configure my spotifyOAuth:



      function spotifyOAuth2Client() {
      // Spotify OAuth 2 setup
      const credentials = {
      client: {
      id: functions.config().spotify.clientid,
      secret: functions.config().spotify.clientsecret,
      },
      auth: {
      tokenHost: 'https://accounts.spotify.com',
      authorizePath: '/authorize'
      },
      };
      return require('simple-oauth2').create(credentials);
      }


      I use that function in this Firebase function that is called using https://us-central1-<my project string>.cloudfunctions.net/redirect:



      exports.redirect = functions.https.onRequest((req, res) => {
      const oauth2 = spotifyOAuth2Client();

      cookieParser()(req, res, () => {
      const state = req.cookies.state || crypto.randomBytes(20).toString('hex');
      console.log('Setting verification state:', state);
      res.cookie('state', state.toString(), {
      maxAge: 3600000,
      secure: true,
      httpOnly: true,
      });
      const redirectUri = oauth2.authorizationCode.authorizeURL({
      redirect_uri: OAUTH_REDIRECT_URI,
      //scope: OAUTH_SCOPES,
      state: state,
      });
      console.log('Redirecting to:', redirectUri);
      res.redirect(redirectUri);
      });
      });


      The code above returns a url string with the proper parameters, the following code block is where my code breaks, I have another cloud function that runs after being redirected from the res.redirect(redirectUri) above. And when I try to run the getToken() method, it appears to not return anything because I hit the catch block instead? This is where I observe the Auth Token Error Not Found.



      const oauth2 = spotifyOAuth2Client();

      try {
      return cookieParser()(req, res, async () => {
      console.log('Received verification state:', req.cookies.state);
      console.log('Received state:', req.query.state);
      if (!req.cookies.state) {
      throw new Error('State cookie not set or expired. Maybe you took too long to authorize. Please try again.');
      } else if (req.cookies.state !== req.query.state) {
      throw new Error('State validation failed');
      }
      console.log('Received auth code:', req.query.code);
      console.log(OAUTH_REDIRECT_URI);

      // Get the access token object (the authorization code is given from the previous step).
      const tokenConfig = {
      code: req.query.code,
      redirect_uri: 'http://localhost:8100/popup'
      };

      // Save the access token
      try {
      const result = await oauth2.authorizationCode.getToken(tokenConfig)
      const accessToken = oauth2.accessToken.create(result);
      console.log('inside try');
      console.log(result);
      console.log(accessToken);
      } catch (error) {
      console.log('Access Token Error', error.message);
      }


      I've double checked my spotify client/secret credentials in the config, what is going wrong with this OAuth2 flow?










      share|improve this question














      I have been working on a oauth2 flow for spotify by following this similar tutorial by the Firebase team for Instagram HERE



      I am able to submit my credentials and return the user code and state in the url, but when I run the method to submit the code to return an auth token, the auth token that I print to console in the Firebase functions returns: Auth Token Error Not Found. Here's my workflow:



      Here's the Spotify docs



      FIRST, I have a function to configure my spotifyOAuth:



      function spotifyOAuth2Client() {
      // Spotify OAuth 2 setup
      const credentials = {
      client: {
      id: functions.config().spotify.clientid,
      secret: functions.config().spotify.clientsecret,
      },
      auth: {
      tokenHost: 'https://accounts.spotify.com',
      authorizePath: '/authorize'
      },
      };
      return require('simple-oauth2').create(credentials);
      }


      I use that function in this Firebase function that is called using https://us-central1-<my project string>.cloudfunctions.net/redirect:



      exports.redirect = functions.https.onRequest((req, res) => {
      const oauth2 = spotifyOAuth2Client();

      cookieParser()(req, res, () => {
      const state = req.cookies.state || crypto.randomBytes(20).toString('hex');
      console.log('Setting verification state:', state);
      res.cookie('state', state.toString(), {
      maxAge: 3600000,
      secure: true,
      httpOnly: true,
      });
      const redirectUri = oauth2.authorizationCode.authorizeURL({
      redirect_uri: OAUTH_REDIRECT_URI,
      //scope: OAUTH_SCOPES,
      state: state,
      });
      console.log('Redirecting to:', redirectUri);
      res.redirect(redirectUri);
      });
      });


      The code above returns a url string with the proper parameters, the following code block is where my code breaks, I have another cloud function that runs after being redirected from the res.redirect(redirectUri) above. And when I try to run the getToken() method, it appears to not return anything because I hit the catch block instead? This is where I observe the Auth Token Error Not Found.



      const oauth2 = spotifyOAuth2Client();

      try {
      return cookieParser()(req, res, async () => {
      console.log('Received verification state:', req.cookies.state);
      console.log('Received state:', req.query.state);
      if (!req.cookies.state) {
      throw new Error('State cookie not set or expired. Maybe you took too long to authorize. Please try again.');
      } else if (req.cookies.state !== req.query.state) {
      throw new Error('State validation failed');
      }
      console.log('Received auth code:', req.query.code);
      console.log(OAUTH_REDIRECT_URI);

      // Get the access token object (the authorization code is given from the previous step).
      const tokenConfig = {
      code: req.query.code,
      redirect_uri: 'http://localhost:8100/popup'
      };

      // Save the access token
      try {
      const result = await oauth2.authorizationCode.getToken(tokenConfig)
      const accessToken = oauth2.accessToken.create(result);
      console.log('inside try');
      console.log(result);
      console.log(accessToken);
      } catch (error) {
      console.log('Access Token Error', error.message);
      }


      I've double checked my spotify client/secret credentials in the config, what is going wrong with this OAuth2 flow?







      firebase oauth-2.0 spotify simple-oauth2






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 20 '18 at 17:08









      Jordan LewallenJordan Lewallen

      479311




      479311
























          1 Answer
          1






          active

          oldest

          votes


















          0














          Resolved my issue, I was not using the correct endpoints:



          const credentials = {
          client: {
          id: functions.config().spotify.clientid,
          secret: functions.config().spotify.clientsecret,
          },
          auth: {
          tokenHost: 'https://accounts.spotify.com',
          authorizePath: '/authorize',
          tokenPath: '/api/token'
          },
          };





          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53398066%2foauth2-fails-to-return-auth-token-using-simple-oauth2-and-firebase-functions-for%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            Resolved my issue, I was not using the correct endpoints:



            const credentials = {
            client: {
            id: functions.config().spotify.clientid,
            secret: functions.config().spotify.clientsecret,
            },
            auth: {
            tokenHost: 'https://accounts.spotify.com',
            authorizePath: '/authorize',
            tokenPath: '/api/token'
            },
            };





            share|improve this answer




























              0














              Resolved my issue, I was not using the correct endpoints:



              const credentials = {
              client: {
              id: functions.config().spotify.clientid,
              secret: functions.config().spotify.clientsecret,
              },
              auth: {
              tokenHost: 'https://accounts.spotify.com',
              authorizePath: '/authorize',
              tokenPath: '/api/token'
              },
              };





              share|improve this answer


























                0












                0








                0







                Resolved my issue, I was not using the correct endpoints:



                const credentials = {
                client: {
                id: functions.config().spotify.clientid,
                secret: functions.config().spotify.clientsecret,
                },
                auth: {
                tokenHost: 'https://accounts.spotify.com',
                authorizePath: '/authorize',
                tokenPath: '/api/token'
                },
                };





                share|improve this answer













                Resolved my issue, I was not using the correct endpoints:



                const credentials = {
                client: {
                id: functions.config().spotify.clientid,
                secret: functions.config().spotify.clientsecret,
                },
                auth: {
                tokenHost: 'https://accounts.spotify.com',
                authorizePath: '/authorize',
                tokenPath: '/api/token'
                },
                };






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 20 '18 at 18:21









                Jordan LewallenJordan Lewallen

                479311




                479311






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53398066%2foauth2-fails-to-return-auth-token-using-simple-oauth2-and-firebase-functions-for%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    MongoDB - Not Authorized To Execute Command

                    How to fix TextFormField cause rebuild widget in Flutter

                    in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith