Helping to understand a token swap service and how to implement one?

Viewed 730

I am after a little advice and some guidance on how to implement a token swap service.

I am trying to implement the steps involved for this SpotifyApi wrapped found (johnnycrazy.github.io/SpotifyAPI-NET/auth/token_swap.html#using-tokenswapwebapifactory)[here].

here is the main code snippet from the link:

TokenSwapWebAPIFactory webApiFactory;
SpotifyWebAPI spotify;

// You should store a reference to WebAPIFactory if you are using AutoRefresh or want to manually refresh it later on. New WebAPIFactory objects cannot refresh SpotifyWebAPI object that they did not give to you.
webApiFactory = new TokenSwapWebAPIFactory("exchangeServerUri")
{
    Scope = Scope.UserReadPrivate | Scope.UserReadEmail | Scope.PlaylistReadPrivate,
    AutoRefresh = true
};
// You may want to react to being able to use the Spotify service.
// webApiFactory.OnAuthSuccess += (sender, e) => authorized = true;
// You may want to react to your user's access expiring.
// webApiFactory.OnAccessTokenExpired += (sender, e) => authorized = false;

try
{
    spotify = await webApiFactory.GetWebApiAsync();
    // Synchronous way:
    // spotify = webApiFactory.GetWebApiAsync().Result;
}
catch (Exception ex)
{
    // Example way to handle error reporting gracefully with your SpotifyWebAPI wrapper
    // UpdateStatus($"Spotify failed to load: {ex.Message}");
}

I have a few questions:

  • What is the purpose of the exchangeServerUri if the result gets returned to the spotifywebapi object?
  • If I place this on startup(do i place it at startup).. how would I access the SpotifyWebAPI object in controllers?

edit:

I have been facing this problem for a while now and would love to get it sorted before the new years as its the only project idea i've had that I could create a website out of.

So essentially my problem is I am consuming the.net wrapper for the spotify api. I am using the basic authentication that the author of the wrapper has used here - https://johnnycrazy.github.io/SpotifyAPI-NET/auth/implicit_grant.html . Using that type of token only allows me to actually use the api when auth has been recieved.. I have to place all my business logic within the AuthReceived event method. The way around that is using another method of authentication is the token swap api which would deal with authenticating independently.

As stated on the doc:

With this approach, you provide the URI/URL to your desired exchange server to perform all necessary requests to Spotify, as well as requests that return back to the "server URI".

The exchange server must be able to:

Return the authorization code from Spotify API authenticate page via GET request to the "server URI".

Request the token response object via POST to the Spotify API token page.

Request a refreshed token response object via POST to the Spotify API token page.

I am just struggling to grasp what the code would look like in the slightest.

1 Answers

Obtaining exchangeServerUri (don't do it just yet)

The same doc you are quoting has a bit more explanation further down:

To keep your client secret completely secure and your client ID and redirect URI as secure as possible, use of a web server (such as a php website) is required.

To use this method, an external HTTP Server (that you may need to create) needs to be able to supply the following HTTP Endpoints to your application:

...........I'm skipping some text for brevity....................

The following open-source token swap endpoint code can be used for your website:

rollersteaam/spotify-token-swap-php

simontaen/SpotifyTokenSwap

So in short you need to stand up a separate webserver and supply it's location to exchangeServerUri.

However

the documentation also states that implementing this Exchange Service only makes sense if you are using authorization_code grant type and are concerned about leaking your Spotify App Secret (read: if you are building a mobile app, where users can potentially reverse-engineer it and extract your secrets). Given your statement about using implicit_grant means this will not apply to you!

If in doubt - check out Spotify's own Auth Guide to see which flow suits you best. Also check Spotify guidelines regarding Token Swap For example of using implicit_grant see here

static async void Main(string[] args)
{
  ImplicitGrantAuth auth = new ImplicitGrantAuth(
    _clientId,
    "http://localhost:4002",
    "http://localhost:4002",
    Scope.UserReadPrivate
  );
  auth.AuthReceived += async (sender, payload) =>
  {
    auth.Stop(); // `sender` is also the auth instance

    SpotifyWebAPI api = new SpotifyWebAPI()
    {
      TokenType = payload.TokenType,
      AccessToken = payload.AccessToken
    };
    // Do requests with API client
  };
  auth.Start(); // Starts an internal HTTP Server
  auth.OpenBrowser();
}

Answer to your second question would greatly depend on what sort of application you're writing, but in general I'd try to persist payload.TokenType and payload.AccessToken and instantiate SpotifyWebAPI where I need it. As far the code example above goes = you can only use the api object within the scope of that particular event handler.

Related