从未调用过 Swift 身份验证挑战 URLSession
Posted
技术标签:
【中文标题】从未调用过 Swift 身份验证挑战 URLSession【英文标题】:Swift Authentication Challenge URLSession never called 【发布时间】:2020-01-01 01:17:19 【问题描述】:我正在尝试访问需要用户名/密码凭据的 API。在调试代码时,我注意到在调用 let session 变量后,它直接进入 session.resume() 并且永远不会调用我的 urlSession 方法来从用户输入中获取用户凭据。
根据我阅读的内容,完成处理程序仍将专门针对身份验证挑战调用委托方法。
运行应用程序不会导致错误,但在后端我得到了这个
“复制匹配凭据时出错。错误=-25300” 和状态码“401”
这是 postReq 函数
func postRequest()
let parameters = ["grant_type=authorization_code&code=xyz"]
guard let url = URL(string: "url to access") else return
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("xyz", forHTTPHeaderField: "X-API-Key")
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.addValue("Basic base64(xyz:xyz)", forHTTPHeaderField: "Authorization")
guard let httpbody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else return
request.httpBody = httpbody
let session = URLSession.shared.dataTask(with: request) (data, response, error) in
if let response = response
print(response)
if let data = data
do
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
catch
print(error)
session.resume()
直接从 swift 文档获取凭据的委托方法和辅助方法
func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
let authMethod = challenge.protectionSpace.authenticationMethod
guard authMethod == NSURLAuthenticationMethodHTTPBasic else
completionHandler(.performDefaultHandling, nil)
return
//Call the completion handler
guard let credential = credentialFromUI() else
completionHandler(.cancelAuthenticationChallenge, nil)
return
completionHandler(.useCredential, credential)
func credentialFromUI() -> URLCredential?
guard let email = emailField!.text, !email.isEmpty,
let password = passField!.text, !password.isEmpty else
return nil
return URLCredential(user: email, password: password, persistence: .forSession)
我也是 Swift 和学习的新手,但我觉得我缺少一些微不足道的东西。
【问题讨论】:
【参考方案1】:如果您在初始请求中提供凭据,则不会请求身份验证质询,因为
request.addValue("Basic base64(xyz:xyz)", forHTTPHeaderField: "Authorization")
您应该删除此行,并在被询问时通过回调提供凭据。
【讨论】:
以上是关于从未调用过 Swift 身份验证挑战 URLSession的主要内容,如果未能解决你的问题,请参考以下文章
Firebase 电话身份验证验证 ID 从未设置。 (颤振iOS)
Pyramid AuthTktAuthenticationPolicy 回调从未调用过
Firebase Google 登录 (iOS) - 从未调用过 GIDSignInUIDelegate 方法