【问题标题】:Basic Auth not working in Alamofire Swift基本身份验证在 Alamofire Swift 中不起作用
【发布时间】:2020-12-29 11:46:45
【问题描述】:

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

获取token using postman.非常简单

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 获取简单令牌的正确方法吗?

【问题讨论】:

  • Postman 将为您提供 Swift 代码。

标签: swift uikit alamofire spotify spotify-app


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-19
    • 1970-01-01
    • 2014-09-06
    • 2014-01-22
    • 2016-01-11
    • 2019-01-30
    • 2016-05-31
    相关资源
    最近更新 更多