Spotify应用程序请求授权
本文介绍了Spotify应用程序请求授权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用以下代码从Spotify获取‘Access Token’。
var encoded = btoa(client_id+':'+client_secret);
function myOnClick() {
console.log('clikced!');
$.ajax({
url: 'https://accounts.spotify.com/api/token',
type: 'POST',
data: {
grant_type : "client_credentials",
'Content-Type' : 'application/x-www-form-urlencoded'
},
headers: {
Authorization: 'Basic ' + encoded
},
dataType: 'json'
}).always((data)=> console.log(data));
}
但是,我一直收到错误:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at https://accounts.spotify.com/api/token.
(Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
和
就绪状态:0,状态:0
推荐答案
来自Spotify的Arielle此处。
看起来您正在使用客户端凭据流,它是您可以与Spotify API一起使用的3个身份验证流之一。(您可以全部签出3here)
客户端凭据仅供服务器端使用,不应在前端使用,因为它需要您不应公开的客户端机密!
您应该改用隐式授予流,它是为在浏览器中使用而设置的。启动和运行起来也很容易!
// Get the hash of the url
const hash = window.location.hash
.substring(1)
.split('&')
.reduce(function (initial, item) {
if (item) {
var parts = item.split('=');
initial[parts[0]] = decodeURIComponent(parts[1]);
}
return initial;
}, {});
window.location.hash = '';
// Set token
let _token = hash.access_token;
const authEndpoint = 'https://accounts.spotify.com/authorize';
// Replace with your app's client ID, redirect URI and desired scopes
const clientId = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
const redirectUri = 'http://localhost:8888';
const scopes = [
'user-read-birthdate',
'user-read-email',
'user-read-private'
];
// If there is no token, redirect to Spotify authorization
if (!_token) {
window.location = `${authEndpoint}?client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scopes.join('%20')}&response_type=token`;
}
要点:https://gist.github.com/arirawr/f08a1e17db3a1f65ada2c17592757049
这里有一个关于Gitch的例子,你可以”Remix”复制并开始制作你的应用程序:https://glitch.com/edit/#!/spotify-implicit-grant
希望有帮助-黑客快乐!