URLSession没有通过标题swift中的'授权'键4

问题描述:

我想通过URLRequest标头中的授权密钥。但在服务器端没有收到密钥。当从邮递员调用相同的API工作正常。标题中的任何其他键都可以正常工作,甚至授权码在服务器端也是可见的。URLSession没有通过标题swift中的'授权'键4

这里是我的代码:

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

我认为这是'Authorization'但不是'authorization'? – chengsam

+0

都尝试,但没有sucess – Santosh

+0

你只需要一个地方来设置AUTH头:'request.setValue( “\(类型)\(标记)”,forHTTPHeaderField: “授权”)' –

我发现同样的事情:设置标题字段授权只是没有把戏。

这是我对结算解决方案(效果很好):

我加入了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还是基本身份验证,这些类型的东西。

最后,这似乎是一个可靠的解决方案。至少,它对我有用。

这里是一个不错的reference document from Apple如果你喜欢读书之类的话。

貌似问题是,你正在修改使用httpAdditionalHeaders这是一件好事,你不应该这样做Authorization头。

Doc

一个NSURLSession对象被设计为处理为你HTTP协议的各个方面。其结果是,你不应该修改以下标题: 授权, 连接, 主机, 代理身份验证, 代理授权, WWW验证

删除线config.httpAdditionalHeaders = headers 应该可以解决这个问题。