如何使用隐式授予流获取应用程序请求授权

时间:2019-11-25 05:05:19

标签: javascript oauth spotify

我正在尝试使用以下代码将用户重定向到Spotify帐户服务的/authorize端点:

        var state = generateRandomString(16);
        function login() {
            var client_id = '02a53684fa064d66a9dff00afeb42fd7';
            var redirect_uri = 'https://localhost:3000';
            var url = new URL('https://accounts.spotify.com/authorize');
            var scope = 'user-read-private user-read-email';
            var params = {
                client_id: client_id,
                response_type: 'token',
                redirect_uri: redirect_uri,
                scope: scope,
                state: state
            };
            url.search = new URLSearchParams(params).toString();
            fetch(url, {
                mode: 'no-cors'
            }).then(response => response.json())
            .catch(error => alert(error));
        }

成功创建了这样的请求网址:

  

https://accounts.spotify.com/login?continue=https%3A%2F%2Faccounts.spotify.com%2Fauthorize%3Fscope%3Duser-read-private%2Buser-read-email%26response_type%3Dtoken%26redirect_uri%3Dhttps%253A%252F%252Flocalhost%253A3000%26state%3DofeflC6YYWLbW7sl%26client_id%3D02a53684fa064d66a9dff00afeb42fd7

尽管已经成功请求了授权访问,但是为什么我在浏览器中看不到Spotify登录屏幕?

1 个答案:

答案 0 :(得分:0)

我前段时间也遇到过同样的问题。如果其他人需要使用JQuery的方法,则可以尝试以下方法:

$.ajax({
    url: auth_url,                      // Authorize url: https://accounts.spotify.com/authorize
    type: 'GET',
    data: {
        client_id: client_id,        // The id given when registering your application.
        redirect_uri: redirect_uri, // The uri specified on the Spotify dashboard.
        scope: scopes,             // Your scopes that the user will authorize.
        response_type: 'token',   // The response type you are expecting.
        state: state             // The randomGenerateString() function from the quick start guide.
    }
}).done(function callback(response) {
    /* Redirect user to home page */
    console.log("Success");
    $(location).attr('href', this.url);  // On success, user will be redirected to your redirect uri you specified on the dashboard.

}).fail(function (error) {
    console.log("Error happened: " + error.status);
    // Handle error ...
});

我对Web开发非常陌生,所以如果我传播不良做法或使事情变得更困难,请原谅我。