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 之一?
实施身份验证质询来处理基本身份验证,例如:
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)
这是参考链接
| 归档时间: |
|
| 查看次数: |
2195 次 |
| 最近记录: |