基本身份验证不适用于Alamofire Swift



我正在尝试获取客户端凭据令牌,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获取简单代币的正确方式吗

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