2

我正在尝试获取客户端凭据令牌,这是 Spotify 的公共 Web API 搜索公共曲目所必需的。

使用邮递员获取令牌非常简单。

REQUEST BODY PARAMETER: VALUE: grant_type Set it to client_credentials. 

The header of this POST request must contain the following parameter:

HEADER PARAMETER: VALUE:  Authorization  Base 64 encoded string that contains the client ID and client secret key. The field must have the format: Authorization: Basic <base64 encoded client_id:client_secret>

我需要在 Swift 中获取 Spotify 令牌。我从这个可解码的结构开始:

struct SpotifyAuth: Decodable {
    var access_token: String
    var expires_in: Int
}

然后,我尝试了以下代码的数十种变体,但均无济于事:

let headers : HTTPHeaders = ["Content-Type":"application/x-www-form-urlencoded"]

let paramaters : Parameters = ["grant_type": "client_credentials", ]

    AF.request("https://accounts.spotify.com/api/token", method: .post, parameters: paramaters, encoding: URLEncoding.httpBody, headers: headers ).authenticate(username: "{clientID}", password:"{clientSecrent}").responseJSON { response in
            if response.error == nil {
                do {
                    let spotifyAuth = try JSONDecoder().decode(SpotifyAuth.self, from: response.data!)

                    completion(.success(spotifyAuth))
                } catch let error {
                    completion(.failure(error))
                }
            } else {
                completion(.failure(response.error!))
            }
        
    }

有谁知道我做错了什么/从 Spotify 获取简单令牌的正确方法?

4

1 回答 1

3

authenticate()用于响应身份验证质询。它不会无条件地添加标题。如果服务器没有响应基本质询,您需要自己添加标头。Alamofire 有一个方便的方法来帮助:HTTPHeader.authorization(username:password:). 这将为您正确生成 Basic 标头。

于 2020-09-11T02:26:00.290 回答