rspotify icon indicating copy to clipboard operation
rspotify copied to clipboard

Authorization Flows

Open mcelicalderon opened this issue 7 years ago • 2 comments

I couldn't find other authorization flow other than the omniauth one. Do you support any other? I was looking for this one in particular https://developer.spotify.com/web-api/authorization-guide/#authorization-code-flow

I already implemented it on my project and would be happy to submit a PR if this is something that you think would work for the gem.

mcelicalderon avatar Jan 25 '18 00:01 mcelicalderon

I also think its better not to be completely dependent on the omniauth flow. It would be nice if the library had a function that took a code from the OAuth flow and made a request to Spotify to basically fetch user access token and other info

ArsalanDotMe avatar Dec 13 '18 13:12 ArsalanDotMe

I wanted exacly what @ArsalanDotMe propose and I end up with this custom flow. I'll share it here if someone else need it.

require 'httparty'

class SpotifyAuthController < ApplicationController

  def spotify_login_url
    query_params = {
      response_type: 'code',
      client_id: ENV['spotify_client_id'],
      scope: 'user-read-email playlist-read-private playlist-read-collaborative user-library-read user-library-modify',
      redirect_uri: 'http://example.com/auth/spotify/callback'
    }

    'https://accounts.spotify.com/authorize?' + query_params.to_query
  end

  def spotify_get_token
    # Get token from code and init Rspotify::User
    body = {
      grant_type: 'authorization_code',
      code: params[:code],
      redirect_uri: 'http://example.com/auth/spotify/callback',
      client_id: ENV['spotify_client_id'],
      client_secret: ENV['spotify_client_secret']
    }

    response = ::HTTParty.post(
      'https://accounts.spotify.com/api/token',
      headers: { 'Content-Type' => 'application/x-www-form-urlencoded' },
      :body => body.to_query
    )

    access_token = response['access_token']

    credentials = Hashie::Mash.new(
      token: access_token,
      refresh_token: response['refresh_token'],
      expires_at: response['expires_in'] + Time.now.to_i,
      expires: true
    )

    response = HTTParty.get(
      'https://api.spotify.com/v1/me',
      headers: { 'Authorization' => "Bearer #{access_token}" }
    )

    user = RSpotify::User.new(**Hashie::Mash.new(response), 'credentials' => credentials)
  end
end

Bhacaz avatar Mar 16 '20 00:03 Bhacaz