简体   繁体   English

Spotify API 授权错误 (Swift)

[英]Spotify API Authorization Error (Swift)

I've made a little App in Swift where a user can search the Spotify database for songs.我在 Swift 中制作了一个小应用程序,用户可以在其中搜索 Spotify 数据库中的歌曲。 I am using the Web API Console > Search for an Item.我正在使用 Web API 控制台 > 搜索项目。 My problem is the new OAuth system where you have to sign-in and all that stuff.我的问题是新的 OAuth 系统,您必须在其中登录和所有这些东西。 My authorization is ok, but when I'm trying to get an access token with the following code, it's returning me the following error: {"error":"server_error","error_description":"Unexpected status: 400"}.我的授权没问题,但是当我尝试使用以下代码获取访问令牌时,它返回以下错误:{"error":"server_error","error_description":"Unexpected status: 400"}。 My code is:我的代码是:

    let keys = "<MY_APPLICATION_KEYS>"

    let url = NSURL(string: "https://accounts.spotify.com/api/token")

    let session = URLSession.shared

    let request = NSMutableURLRequest(url: url! as URL)

    request.httpMethod = "POST"

    request.setValue("Basic \(keys)", forHTTPHeaderField: "Authorization")

    request.setValue("client_credentials", forHTTPHeaderField: "grant_type")

    let task = session.dataTask(with: request as URLRequest) { (data, response, error) in

        guard let _: Data = data, let _: URLResponse = response, error == nil else {

            print(error!)
            return

        }

        let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
        print("Data: \(dataString!)")

        self.parseData(JSONData: data!)

    }

    task.resume()

}

var accessToken = ""

func parseData(JSONData : Data) {

    do {
        var readableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as! JSONStandard

        if let token = readableJSON["access_token"] as? String {

            accessToken = token

        }

        print("Access Token: \(accessToken)")

        updateTokenInFirebase()

    }
    catch{
        print(error)
    }

Any help would be very appreciated, thank you very much in advance!任何帮助将不胜感激,非常感谢您提前!

Documentation of the Web API: Web API Link Web API 的文档: Web API 链接

I am using on the Client Credentials Flow the first method.我在客户端凭据流上使用第一种方法。

I know it's been ~1 year since you posted this but I had the same issue and after a few tries was able to get it.我知道你发布这个已经有大约 1 年了,但我遇到了同样的问题,经过几次尝试后终于解决了。 You can test this in Playground.您可以在 Playground 中对此进行测试。

import Foundation
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

if let url = URL(string: "https://accounts.spotify.com/api/token") {
    var postRequest = URLRequest(url: url)
    postRequest.httpMethod = "POST"
    let bodyParams = "grant_type=client_credentials"
    postRequest.httpBody = bodyParams.data(using: String.Encoding.ascii, allowLossyConversion: true)

    let id = "your client id"
    let secret = "your secret"
    let combined = "\(id):\(secret)"
    let combo = "\(id):\(secret)".toBase64()
    postRequest.addValue("Basic \(combo)", forHTTPHeaderField: "Authorization")

    let task = URLSession.shared.dataTask(with: postRequest) { (data, response, error) in
        guard let data = data else {
            return
        }
        print(String(data: data, encoding: String.Encoding.utf8)!)
    }
    task.resume()
}


extension String {

    func fromBase64() -> String? {
        guard let data = Data(base64Encoded: self) else {
            return nil
        }

        return String(data: data, encoding: .utf8)
    }

    func toBase64() -> String {
        return Data(self.utf8).base64EncodedString()
    } 
}

I know this is really late, but the issue is with this line:我知道这真的很晚了,但问题在于这一行:

request.setValue("client_credentials", forHTTPHeaderField: "grant_type")

According to the authorization guide , this should be in the body of the request, not the headers.根据授权指南,这应该在请求的正文中,而不是标题中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM