2

I'm building a library for redirecting all requests in a whitelist to a different host. There are several examples out there about how to do this so most of the the work on that front is finished. The library makes some modifications to the original request if it is in the whitelist, such as encryption, modifications to the body of the request and more. I'm now trying to integrate websocket redirection into the library as well, as the request for the websocket (if in the whitelist) needs to be modified and redirected. the idea is for all underlying tasks to be handled transparently, so the developer using the library doesnt have to handle any of the redirection.

I am using URLprotocol which for normal HTTP requests works perfectly, where each request is passed to my URL protocols 'canInit' function where it is determined if it is in the whitelist or not, then either handled or not. however a websocket upgrade request is never seen by 'canInit', and so i cant modify the request.

Is it possible to intercept a URLSessionWebSocketTask HTTP upgrade request? either using URLProtocol or another method?

thanks to anyone for their response

Edit: code is proprietary, so adding some sudo code to show implementation.

class MyURLProtocol: NSURLProtocol {
  override class func canInit(request: NSURLRequest) -> Bool {
    println("URL = \(request.URL.absoluteString)")
    if (url is in whitelist) {
      return true
    }
    return false
  } 
}

As shown, I print all requests which are passed to the handler, but no ws:// or wss:// requests are ever passed to the handler.

Tokens94
  • 113
  • 1
  • 8
  • WebSocket upgrade requests should be seen by `canInit`. By the way, the initial upgrade request is the only request related to WebSockets that URLProtocol can see. None of the subsequent exchanged messages trigger any of the URLProtocol methods. Are you sure you're configuring it correctly? Perhaps you could provide a code snippet for us to verify. – Alex Machado Nov 20 '20 at 20:03
  • Yes I'm aware that only the upgrade request is in http(s), before it is then 'upgraded' to a websocket, but that request does not get parsed to the handler. Thanks for your response – Tokens94 Dec 10 '20 at 16:48
  • I don't know how relevant this is now, but in my case intercept HTTP upgrade request works fine. I've faced with next problem - can't return URLResponse back to webSockets for handshake. – olle Aug 23 '22 at 09:32
  • 1
    @AlexMachado could you please explain why do you think that none of the next messages trigger any of the URLProtocol methods? I don't see any limitation in documentation. – olle Aug 23 '22 at 09:39

0 Answers0