且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Django中使用spotify api身份验证重定向uri,该怎么办?

更新时间:2023-12-01 09:22:34

为了实现这一点,我最终放弃了spotipy模块,只是使用javascript。我看到您使用用户授权API流程,因为您的服务器可以安全地发送您的密钥。将其移动到应用程序的前端时,您不能这样做,而是必须使用隐性赠款流程:

 #在您的主页的< script&gt ;: 
var loginSpotify = function(){
var SPOTIPY_CLIENT_ID =您的客户端ID
var SPOTIPY_REDIRECT_URI =您的Django回调查看此处(www.example.com/callback/)
var spotifyScope =playlist-read-private
var spotifyAuthEndpoint =https://accounts.spotify.com/authorize?\"+\"client_id=\"+SPOTIPY_CLIENT_ID+\"&redirect_uri=\"+SPOTIPY_REDIRECT_URI+\"&范围= + spotifyScope + &安培; RESPONSE_TYPE =令牌安培;状态= 123\" ;
window.open(spotifyAuthEndpoint,'callBackWindow','height = 500,width = 400');
//这个事件监听器会在你的回调页面添加到localStorage
window.addEventListener(storage,function(event){
if(event.key ==accessToken ){
var spAccessToken = event.newValue;
//使用您的访问令牌在Spotify API中执行操作!
}
});
}

调用上述方法将打开一个新的弹出窗口,让用户通过spotify的登录一旦授权,该窗口将重定向到您指定的Django视图。该视图加载回调页面,其唯一目的是从其URI中收集访问令牌:

 #在您的视图中。 py:
def callback(request):
return render(request,'YourApp / spotifyLoginFinish.html',{})

当该页面加载时,在弹出窗口中,它的URI将包含您要求的资源,例如: http://www.example.com/callback/ #的access_token = BQDoPzyrkeWu7xJegj3v1JDgQXWzxQk2lgXrQYonXkXIrhmjeJVS38PFthMtffwlkeWJlwejkwewlHaIaOmth_2UJ2xJrz2x-Voq0k0T0T4SuCUdIGY3w3cj5CpULkFla9zwKKjvdauM2KoUIQa1vULz-w8Da83x1&安培; token_type =承载&安培; expires_in = 3600&安培;状态= 123



如果youre使用jquery或没有,但IDK这是一种在页面加载时调用JS函数的方法。所以现在所有你需要做的是解析URI一旦回调页面加载,你可以获得你的访问令牌。然后,您完成了此弹出式回调窗口,因此您可以通过将访问令牌添加到localStorage来将访问令牌传递回主页面。记住在主页上我们创建了一个事件监听器来观看本地存储,所以你会知道它在那里。以下是您在回调页面上需要的代码示例(它使用一些jquery,但是有常规的JS方式在页面加载时执行某些操作):

  #In spotifyLoginFinish.html的< script&gt ;: 
$('document')。ready(function(){
//我将'parseHash()'作为一个练习对于读者而言,它所做的只是使用uri字符串(请参见上面的ex),并从中获取access_token
var spotifyAccessToken = parseHash(String(window.location.hash));
//您必须清除主页面监听器的localStorage以触发所有(包括重复)条目
localStorage.clear();
localStorage.setItem('accessToken',spotifyAccessToken);
窗口.close();
});

现在你的弹出窗口已经关闭了,你回到主窗口,在localStorage事件监听器函数中这篇文章中的第一段代码。它将从localStorage中获取令牌,并且所有设置!希望这有帮助,请不要发表评论。


I've built an app in Django that uses Spotipy, a Spotify API Python Library, and uses the spotipy.util.prompt_for_user_token() command as such to generate a token and access my private library as such:

import spotipy
import spotipy.util as util
import os, ast

#Spotify API keys
scope = "playlist-read-private"
uir = "http://localhost:8000"
username = "<MY_USERNAME>"

spotify_uid = os.environ["SPOTIFY_UID"]
spotify_usec = os.environ["SPOTIFY_USEC"]
print "retrieved keys from OS"

#set up access
def get_access():
  try:
    token = util.prompt_for_user_token(username, scope, spotify_uid, spotify_usec, uir)
    print "SUCCESS"
    return spotipy.Spotify(auth=token)
  except:
    print "FAILED TO LOAD"

I'd like the app to have a ui login instead of a hardcoded login, but I can't figure out how.

At the moment I have a 'login' button which attempts to trigger the login page redirect through Javascript, by calling the above code with a username parameter, but that opens a new page and the following is in the console:

User authentication requires interaction with your
        web browser. Once you enter your credentials and
        give authorization, you will be redirected to
        a url.  Paste that url you were directed to to
        complete the authorization.


Opening https://accounts.spotify.com/authorize?scope=playlist-read-     private&redirect_uri=http%3A%2F%2Flocalhost%3A8000&response_type=code&client_id=<CLIENT_ID> in your browser


Enter the URL you were redirected to: [30/Jun/2016 15:53:54] "GET /?code=<TOKEN>HTTP/1.1" 200 2881 

note: the text in carat brackets were replaced since they were private keys.

I'd like it to have similar functionality to how this website handles logins: http://static.echonest.com/SortYourMusic/

To implement this I ended up abandoning the spotipy module all together and just using javascript. I see your using the user authorization api flow which is fine because your server can send your secret key securely. When moving this to the frontend of your application you can't do this and instead must use the Implicit Grant flow:

#In your main page's <script>:
var loginSpotify = function(){
        var SPOTIPY_CLIENT_ID = "Your Client ID Here"
        var SPOTIPY_REDIRECT_URI = "Your Django Callback View Here (www.example.com/callback/)"
        var spotifyScope = "playlist-read-private"
        var spotifyAuthEndpoint = "https://accounts.spotify.com/authorize?"+"client_id="+SPOTIPY_CLIENT_ID+"&redirect_uri="+SPOTIPY_REDIRECT_URI+"&scope="+spotifyScope+"&response_type=token&state=123";
        window.open(spotifyAuthEndpoint,'callBackWindow','height=500,width=400');
        //This event listener will trigger once your callback page adds the token to localStorage
        window.addEventListener("storage",function(event){
            if (event.key == "accessToken"){
                var spAccessToken = event.newValue;
                //do things with spotify API using your access token here!!
            }
        });
    }

Calling the above method will open a new popup window that will take the user through spotify's login. Once authorized, the window will redirect to the Django view you specify. Have that view load a callback page whose only purpose will be to collect the access token from its URI:

#in your views.py:
def callback(request):
    return render(request, 'YourApp/spotifyLoginFinish.html',{})

When that page loads, in the popup window, it's URI will contain the grant you seek, ex: http://www.example.com/callback/#access_token=BQDoPzyrkeWu7xJegj3v1JDgQXWzxQk2lgXrQYonXkXIrhmjeJVS38PFthMtffwlkeWJlwejkwewlHaIaOmth_2UJ2xJrz2x-Voq0k0T0T4SuCUdIGY3w3cj5CpULkFla9zwKKjvdauM2KoUIQa1vULz-w8Da83x1&token_type=Bearer&expires_in=3600&state=123

Idk if youre using jquery or not but theres a bunch of ways to call a JS function on page load. So now all you need to do is parse the URI once the callback page loads and you can get your access token. Then you're done with this popup callback window, so you can pass the access token back to your main page by adding it to localStorage. Remember how on your main page we created an event listener to watch the localStorage so you'll know when its there. Here's an example of the code you'd want on your callback page (it uses some jquery but there are regular JS ways of doing stuff on page load):

#In spotifyLoginFinish.html's <script>:
$('document').ready(function(){
        //i leave 'parseHash()' as an exercise for the reader, all it does is take the uri string(see above ex of what this looks like) and get the access_token from it
        var spotifyAccessToken = parseHash(String(window.location.hash));
        //you must clear localStorage for main page listener to trigger on all(including duplicate) entries
        localStorage.clear();
        localStorage.setItem('accessToken', spotifyAccessToken);
        window.close();
});

Now your popup has closed itself and youre back in your main window, in the localStorage event listener function from the first piece of code in this post. It'll get the token from localStorage and youre all set! Hope this helps, please comment if it doesn't work.