Trying to use oauth flow in Electron desktop app (with spotify API)?

Viewed 764

I have a React app in Electron, and I'm trying to access the spotify API using the spotify-web-api-node library. However, I'm not sure exactly how the oauth flow is meant to work inside of an Electron app... Firstly, for the redirect URL, I used this question and added a registerFileProtocol call to my file. Then I added a specific ipcMain.on handler for receiving the spotify login call from a page, which I've confirmed works with console logs. However, when I get to actually calling the authorizeURL, nothing happens?

This is part of my main.js:

app.whenReady().then(() => {
...
  protocol.registerFileProtocol(
    "oauthdesktop",
    (request, callback) => {
      console.log("oauthdesktop stuff: ", request, callback);
      //parse authorization code from request
    },
    (error) => {
      if (error) console.error("Failed to register protocol");
    }
  );
});

ipcMain.on("spotify-login", (e, arg) => {
  const credentials = {
    clientId: arg.spotifyClientId,
    clientSecret: arg.spotifySecret,
    redirectUri: "oauthdesktop://test",
  };

  const spotifyApi = new SpotifyWebApi(credentials);
  console.log("spapi: ", spotifyApi);

  const authorizeURL = spotifyApi.createAuthorizeURL(
    ["user-read-recently-played", "playlist-modify-private"],
    "waffles"
  );
  console.log("spurl: ", authorizeURL);

  axios.get(authorizeURL);
}

I'd expect the typical spotify login page popup to show up, but that doesn't happen. I'd also expect (possibly) the registerFileProtocol callback to log something, but it doesn't. What am I meant to be doing here? The authorization guide specifically mentions doing a GET request on the auth url, which is what I'm doing here...

1 Answers

In a desktop app it is recommended to open the system browser, and the Spotify login page will render there, as part of creating a promise. The opener library can be used to invoke the browser.

When the user has finished logging in, the technique is to receive the response via a Private URI Scheme / File Protocol, then to resolve the promise, get an authorization code, then swap it for tokens. It is tricky though.

RESOURCES OF MINE

I have some blog posts on this, which you may be able to borrow some ideas from, and a couple of code samples you can run on your PC:

The second of these is a React app and uses a Private URI scheme, so is fairly similar to yours. I use the AppAuth-JS library and not Spotify though.

Related