我正在尝试在URLRequest的标头中传递授权密钥。但是在服务器端没有收到密钥。从邮递员工作正常时调用相同的API。标题中的任何其他键工作正常,甚至授权键在服务器端也可见。
这是我的代码:
let headers = [
"authorization": "token abcd"
]
var request = URLRequest.init(url: NSURL(string:
"http://127.0.0.1:7000/api/channels?filter=contributed")! as URL)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
let config = URLSessionConfiguration.default
config.httpAdditionalHeaders = headers
let session = URLSession.init(configuration: config)
let dataTask = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error ?? "")
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse ?? "")
}
})
正如您所看到的,我尝试在会话配置和请求中设置令牌,但没有一个正在运行。
答案 0 :(得分:5)
这似乎有效:
// Set the security header
private var credentials: String {
return "\(participantId):\(password)"
}
private var basicAuthHeader: String {
return "Basic \(credentials)"
}
func getSettings(participantId: Int, password: String) -> Bool {
self.participantId = participantId
self.password = password
let path = "/settings/\(participantId)"
guard let url = URL(string: "\(BASE_URL)\(path)") else {
Log.e("Invalid URL string, could not convert to URL")
return false
}
var urlRequest = URLRequest(url: url)
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.setValue(basicAuthHeader, forHTTPHeaderField: "Authorization")
urlRequest.setValue(APP_FILE_NAME, forHTTPHeaderField: "User-Agent")
// This is a synchronous wrapper extension around URLSession.dataTask()
let (data, response, error) = URLSession.shared.synchronousDataTask(with: urlRequest)
// Process the result...
}
注意:我的同事写的代码。谢谢约翰!
答案 1 :(得分:0)
我发现了同样的事情:设置标题字段授权只是没有做到这一点。
这是我确定的解决方案(效果很好):
我将URLSessionDelegate协议添加到我当前的类中。遗憾的是,这意味着继承自NSObject。
然后,在定义我的URLSession时,我将其委托设置为'self'。
最后,我提供了一个身份验证质询处理程序。
在代码中,这看起来像是:
public class SomeHTTPTask: NSObject, URLSessionDelegate {
public init() {
... initialize variables ...
super.init()
... now you are free to call methods on self ...
}
public func httpTask(withURL url: URL) {
let request = URLRequest(url: url)
... set up request ...
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
let task = session.dataTask(with: request) {data, response, error in
... now you have a result ...
}
}
public func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
guard let user = Credentials.sharedInstance.userId, let password = Credentials.sharedInstance.password else {
completionHandler(.performDefaultHandling, nil)
return
}
let userCredential = URLCredential(user: user,
password: password,
persistence: .permanent)
completionHandler(.useCredential, userCredential)
}
}
希望这些点点滴滴都是不言自明的。它只是一个提供凭据的身份验证质询处理程序,如果可以的话。底层的URLSession将处理细节,无论是NTLM还是Basic auth,都是这样的。
最后,这似乎是一个可靠的解决方案。至少,它对我有用。
如果你喜欢阅读那种东西,这是一个很好的reference document from Apple。
答案 2 :(得分:0)
看起来问题是您正在使用Authorization
修改httpAdditionalHeaders
标头,这是您不应该做的事情。
来自Doc
NSURLSession对象旨在为您处理HTTP协议的各个方面。因此,您不应修改以下标头: 授权 连接, 主办, 代理服务器进行身份验证, 代理授权, WWW身份验证
删除行config.httpAdditionalHeaders = headers
应该可以解决问题。
答案 3 :(得分:0)
如果你想对令牌进行硬编码,我想它必须是这样的:
urlRequest.httpMethod = "GET"
urlRequest.setValue("Token <Your Token>", forHTTPHeaderField: "Authorization")