Published in


Spotify Authentication Flow Example With Ruby Webrick Webserver

This tutorial will replace Node.js with Ruby in the Authentication Flow example app for Spotify Web API.

This flow first gets a code from the Spotify Accounts Service, then exchanges that code for an access token. The code-to-token exchange requires a secret key, and for security is done through direct server-to-server communication.

In this example we retrieve data from the Web API /me endpoint, that includes information about the current user.

Here we will use Ruby for server-side applications.

Setup Webserver

Many web server gems could accept and process requests. In this tutorial, I tried using Webrick.

WEBrick is an HTTP server toolkit that can be configured as an HTTPS server, a proxy server, and a virtual-host server.

First, you need to initialize the Gemfile and add webrick gem.

Then add gem 'webrick' to your Gemfile and run bundle install to install the gem. Your Gemfile should look like this.

Then you should create a server.rb file so we can start building the web server.

We are going to add a RequestHandler class to our web server and kill the server with crtl+c .


We added a simple web servlet that will process the requests. This will send the request and response objects to a method; otherwise, raise an error which means that the route doesn’t exist. Also, we need to require this file in our server file.

Adding Actions

We will add basic actions so the user can see a Login With Spotify button, click on it, and be redirected to Spotify to grant access to our application and return. I’m using the OAuth examples on the Spotify Web API document page for the HTML pages.


First, create a templates directory and add an index.html to it with the content below.

Now we will add the request handler for this. Create a request_handlers directory and add index.rb file. With the logic we had in request_handler.rb file, we need a method called process_ACTION-NAME to handle the request, which in this case, will be process_ and the action name will be empty.

After this, we need to modify our server.rb file and require this new ruby file.

Also, I moved a couple of lines to a helper called response.rb for rendering HTML pages.

# request_handlers/index.rb

# frozen_string_literal: true

def process_(_, response)
result ='templates/index.html')
render_html(result, response)
# server.rb
require_relative 'helpers/response'

Now, if everything is fine you could start the web server with $ ruby server.rb command and in your browser http://localhost:8000 should serve something like this.

Now, this button will send the user to localhost:8000/login which will redirect the user to the Spotify website. Now let’s add the logic for /login .

Login Action

We have followed the details mentioned in Spotify Authorization Code Flow documentation.

# server.rb

require 'securerandom'
require_relative 'request_handlers/login'
$scopes = %w[ user-read-private
playlist-modify-private].join(' ')

$client_id = 'YOUR_APP_CLIENT_ID'
$client_secret = 'YOUR_APP_CLIENT_SECRET
$callback_url = "http://localhost:#{port}/callback"

You need to add your app client id and client secret here. Also, change the required scopes based on Spotify Authorization Scopes.

Now you need to restart the webserver and now click on Login with Spotify button and should be redirected to the Spotify website for login and granting access.

When you finish, you’ll be redirected back to http://localhost:8000/callback which we are going to add next.

Callback Action

Whenever the user returns to the callback action, we need to obtain a token with the given code in the query params.

If the user accepted your request, then your app is ready to exchange the authorization code for an Access Token. It can do this by making a POST request to the /api/token endpoint.

Also, we need to modify our server.rb file to require more items.

Firstly, we check the given state with the spotify_auth_statecookie to ensure the user is the same; otherwise, it’s an error, and we should not proceed. Then we need to get the token from Spotify API and redirect the user to a profile page called /me .

me Action

First, we added the HTML page from OAuth examples on the Spotify Web API documentation page.

Now we need an action to render this page.

# server.rb
require_relative 'request_handlers/me'

Now, if you restart your web server and grant access to the application with your Spotify account, in the end, you should see a page like this.

Refresh Token Action

Each Access Token is valid for 1 hour, and you need to obtain a new access token with your refresh token. On this page, there is a Obtain new token using the refresh token button, which will make a request to our web server and ask for a new access token. The action is called /refresh_token and need to return the response with application/json Content-Type header.

First, we are going to add render_json method to our helper.

Now we are going to add the refresh_token action and modify our server.rb file as well.

# server.rb

require_relative 'request_handlers/refresh_token'

You can finally clone all the files from azolf/spotify-web-api-auth-examples-ruby repository on Github.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Amirhosein Zlf

A back-end developer who loves to watch Football, Formula1, and Snooker | Real Madrid, Mercedes AMG Petronas F1 Team, Ronnie O’Sullivan, and also a Coldplay fan