Swift 5 URLRequest 授权头:保留,如何设置?

Pau*_*der 8 authentication macos http-headers ios swift

Swift在 Foundation 中的 URLRequest文档中,它说为 URLRequest 设置标头值的标准方法不应用于保留的 HTTP 标头。

按照文档中更深入的保留 HTTP 标头列表的链接,它说它可能会忽略设置这些标头的尝试。

但它也说这Authorization是一个保留的 HTTP 标头。

这不可能是对的,对吗?Universe 中的大部分 API 都要求您在表单的标头中传递身份验证令牌Authorization: Bearer {token}

因此,如果 Swift 不允许您设置Authorization标头,那么如何访问这些 API 之一?

Rac*_*wal 0

实施身份验证质询来处理基本身份验证,例如:

func urlSession(_ session: URLSession,
                didReceive challenge: URLAuthenticationChallenge,
                completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
    switch challenge.protectionSpace.authenticationMethod {
    case NSURLAuthenticationMethodHTTPBasic:
        performBasicAuthentication(challenge: challenge, completionHandler: completionHandler)
    default:
        completionHandler(.performDefaultHandling, nil)
    }
}

func performBasicAuthentication(challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
    let credential = URLCredential(user: "username", password: "password", persistence: .forSession)
    completionHandler(.useCredential, credential)
}
Run Code Online (Sandbox Code Playgroud)

这是参考链接