firebaseoauth-2.0spotifysimple-oauth2

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


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?


Solution

  • 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'
        },
    };