我该如何处理 Django 中的 Spotify api 身份验证重定向 uri? [英] What do I do with a spotify api authentication redirect uri in Django?

查看:23
本文介绍了我该如何处理 Django 中的 Spotify api 身份验证重定向 uri?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Django 中构建了一个应用程序,它使用 Spotipy,一个 Spotify API Python 库,并使用 spotipy.util.prompt_for_user_token() 命令来生成令牌并访问我的私人库像这样:

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"

我希望应用程序具有 ui 登录名而不是硬编码登录名,但我不知道如何进行.

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

目前我有一个登录"按钮,它尝试通过 Javascript 触发登录页面重定向,方法是使用用户名参数调用上面的代码,但这会打开一个新页面,控制台中显示以下内容:

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 

注意:克拉方括号中的文字已被替换,因为它们是私钥.

我希望它具有与本网站处理登录方式类似的功能:http://static.echonest.com/SortYourMusic/

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

推荐答案

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

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!!
            }
        });
    }

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

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',{})

当网页加载,在弹出的窗口,它的URI将包含授予你寻找,例如:<代码> http://www.example.com/callback/#access_token=BQDoPzyrkeWu7xJegj3v1JDgQXWzxQk2lgXrQYonXkXIrhmjeJVS38PFthMtffwlkeWJlwejkwewlHaIaOmth_2UJ2xJrz2x-Voq0k0T0T4SuCUdIGY3w3cj5CpULkFla9zwKKjvdauM2KoUIQa1vULz-w8Da83x1&token_type=Bearer&expires_in=3600&state=123

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 如果您使用 jquery,但有很多方法可以在页面加载时调用 JS 函数.因此,现在您需要做的就是在回调页面加载后解析 URI,然后您就可以获得访问令牌.然后你完成了这个弹出回调窗口,所以你可以通过将访问令牌添加到 localStorage 来将它传递回你的主页.记住我们如何在您的主页上创建一个事件侦听器来监视 localStorage,以便您知道它何时出现.这是您需要在回调页面上使用的代码示例(它使用了一些 jquery,但在页面加载时有一些常规的 JS 方法):

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();
});

现在您的弹出窗口已经关闭,您又回到了主窗口,在本文第一段代码的 localStorage 事件侦听器函数中.它将从 localStorage 获取令牌,一切就绪!希望能帮到你,如果不行请评论.

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.

这篇关于我该如何处理 Django 中的 Spotify api 身份验证重定向 uri?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆