2017-09-02 257 views
1

我试图让我的应用程序通过他们的Authorization Code Flow登录Spotify。我能设法得到一个访问令牌时从Spotify的接收授权code在初始授权步骤,但收到以下错误:Spotify授权代码

{"error":"invalid_client","error_description":"Invalid client"}

我的代码如下:

# Callback from Spotify Authorization 
get '/auth/spotify/callback' do 
    session[:code] = params[:code] 
    redirect to '/refresh' 
end 

然后,我张贴如下:

get '/refresh' do 
    uri = URI('https://accounts.spotify.com/api/token') 
    resp = Net::HTTP.post(uri, 
    { 
     "grant_type" => "authorization_code", 
     "code" => session[:code].to_s, 
     "redirect_uri" => "http://localhost:4567/auth/spotify/callback", 
     "client_id" => client_id, 
     "client_secret" => client_secret 
    }.to_json 
) 
    "#{resp.body}" 
end 

任何帮助,将不胜感激

编辑:我也试过使用PostMan POST上述相同的参数,但收到相同的错误消息

+0

这看起来像一个非常典型的OAuth2流程的正确方法。为了简单起见,您可能需要考虑使用[oauth2](https://github.com/intridea/oauth2)之类的内容。 – coreyward

回答

1

您需要在您的POST请求中添加授权标头。

添加以下关键在你的Net :: HTTP.post选项:

{'Authorization' => 'Basic YOUR_AUTH_CODE' }

编辑:

这是'Your application requests refresh and access tokens'标题下的文档。

+0

是的,我见过这个。但是'Authorzation'部分下方还有一段代码,说你可以在你的body中包含你的非base64编码id和秘密。无论如何,我试过你的方式,仍然收到相同的错误 – Andy

+0

你仍然可以尝试添加授权标题并删除client_id,secret_id键吗? – MaieonBrix

+0

如果我添加一个头文件,错误信息变为'{“error”:“unsupported_grant_type”,“error_description”:“grant_type必须是client_credentials,authorization_code或refresh_token”} SEE:https://gist.github.com/ mindovermiles262/66ff2fc1da8c4c6220365f16845ca8ae – Andy

1

要回答我的问题:

我并不需要做,因为我用,'omniauth-spotify'创业板的要求,可以在request.env['omniauth.auth'].credentials.token

我也创建访问令牌还给我POST请求不正确。下面的例子是使一个POST,将获得从refresh_token新令牌(在上述.credentials散列提供)

# Get new access token from refresh token 
# session[:creds] = request.env['omniauth.auth'].credentials 

get '/refresh' do 
    refresh_token = session[:creds].refresh_token 
    auth = "Basic " + Base64.strict_encode64("#{client_id}:#{client_secret}") 
    uri = URI.parse('https://accounts.spotify.com/api/token') 
    request = Net::HTTP::Post.new(uri) 
    request["Authorization"] = auth 
    request.set_form_data(
    "grant_type" => "refresh_token", 
    "refresh_token" => refresh_token, 
) 

    req_options = { 
    use_ssl: uri.scheme == "https", 
    } 

    response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http| 
    http.request(request) 
    end 

    "#{response.code}" # > 200 OK 

end